【问题标题】:Using Backbone.js Models/Collections with static JSON使用带有静态 JSON 的 Backbone.js 模型/集合
【发布时间】:2012-10-18 21:18:03
【问题描述】:

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

我在这里尝试的是一个简单的应用程序,它在加载时提取 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;
  }
});

【问题讨论】:

    标签: javascript backbone.js backbone.js-collections


    【解决方案1】:

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

    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();
        }
    });
    

    【讨论】:

    • 非常感谢您提供的示例!那么,在这种情况下,使用集合的优势在哪里呢?我的意思是,我不能用我自己的 ajax 调用和缓存结果做同样的事情吗?我为他们和模型看到的所有示例似乎都非常关注将数据保存到服务器。这是唯一的用例吗?
    猜你喜欢
    • 2016-05-19
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2015-03-18
    • 1970-01-01
    相关资源
    最近更新 更多