javascript - 使用带有静态 JSON 的 Backbone.js 模型/集合

标签 javascript backbone.js backbone.js-collections

我正试图通过直接投入并构建一个简单的“问题”应用程序来学习 Backbone,但我一直在用头撞墙试图弄清楚如何正确使用模型和/或集合。我已经将代码添加到我迷路的地方。我能够让集合提取 JSON 文件(执行“var list = new QuestionList; list.getByCid('c0') 似乎返回第一个问题),但我不知道如何更新模型,将当前模型用于 View 的数据,然后在单击“下一步”按钮时如何使用下一个问题更新模型。

我想在这里得到的是一个简单的应用程序,它在加载时提取 JSON,显示第一个问题,然后在按下按钮时显示下一个问题。

谁能帮我把这些点联系起来?

/questions.json

[
  {
    questionName: 'location',
    question: 'Where are you from?',
    inputType: 'text'
  },
  {
    questionName: 'age',
    question: 'How old are you?',
    inputType: 'text'
  },
  {
    questionName: 'search',
    question: 'Which search engine do you use?'
    inputType: 'select',
    options: {
      google: 'Google',
      bing:   'Bing',
      yahoo:  'Yahoo'
    }
  }
]

/app.js

var Question = Backbone.Model.Extend({});
var QuestionList = Backbone.Collection.extend({
  model: Question,
  url: "/questions.json"
});

var QuestionView = Backbone.View.extend({
  template: _.template($('#question').html()),
  events: {
    "click .next" : "showNextQuestion"
  },
  showNextQuestion: function() {
    // Not sure what to put here? 
  },
  render: function () {
    var placeholders = {
      question: this.model.question, //Guessing this would be it once the model updates
    }
    $(this.el).html(this.template, placeholders));
    return this;
  }
});

最佳答案

很明显,在当前设置中, View 需要访问比其单一模型更大的范围。我可以看到这里有两种可能的方法。

1) 将集合(使用 new QuestionView({ collection: theCollection }))而不是模型传递给 QuestionView。维护一个索引,您可以在单击事件时递增并重新呈现该索引。这应该看起来像:

var QuestionView = Backbone.View.extend({

  initialize: function() {
     // make "this" context the current view, when these methods are called
     _.bindAll(this, "showNextQuestion", "render");
     this.currentIndex = 0;
     this.render();
  }      
  showNextQuestion: function() {
     this.currentIndex ++;
     if (this.currentIndex < this.collection.length) {
         this.render();
     }
  },
  render: function () {
    $(this.el).html(this.template(this.collection.at(this.currentIndex) ));
  }
});

2) 设置Router并在点击事件上调用 router.navigate("questions/"+ index, {trigger: true})。像这样:

var questionView = new QuestionView( { collection: myCollection });

var router = Backbone.Router.extend({
    routes: {
        "question/:id": "question"
    },

    question: function(id) {
        questionView.currentIndex = id;
        questionView.render();
    }
});

关于javascript - 使用带有静态 JSON 的 Backbone.js 模型/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12963912/

相关文章:

javascript - 了解用户何时点击任何 iframe 的更简单方法?

javascript - 为什么我在 Angular2 中的自定义验证不起作用

javascript - 主干 View 不显示

javascript - Backbone.Collection 获取第一个 n 作为新集合

javascript - 将 jQuery UI Sortable 的顺序保存到 Backbone.js 集合

javascript - 如何根据复选框列选择表格中的行

javascript - Highcharts 堆积条形图变空

apache - Backbone.js 路由器在本地主机上使用 pushstate 和 XAMPP apache 服务器

javascript - 使用backbonejs作为付费服务网站是不是一个坏主意?

javascript - Backbone.js 集合获取,无法检索项目