Backbone.Collection.Create不会在视图中触发"添加"

Sne*_*bat 2 backbone.js

希望这是一个简单的问题.我正在努力学习骨干,我坚持一个非常简单的事情.当我使用create方法更新集合时,视图上的渲染永远不会被调用.我认为这应该在没有显式调用render的情况下发生 我没有加载任何动态的东西,在这个脚本触发之前它都在dom中.click事件工作正常,我可以将新模型添加到集合中,但视图中的渲染永远不会触发.

$(function(){

window.QuizMe = {};

// create a model for our quizzes
QuizMe.Quiz = Backbone.Model.extend({
// override post for now
"sync": function (){return true},

});

QuizMe._QuizCollection = Backbone.Collection.extend({
model: QuizMe.Quiz,
});

QuizMe.QuizCollection = new QuizMe._QuizCollection

QuizMe.QuizView = Backbone.View.extend({

el:$('#QuizMeApp'),

template: _.template($('#quizList').html()),

events: {
  "click #addQuiz" : "addQuizDialog",
},

initialize: function() {
// is this right?
  _.bindAll(this,"render","addQuizDialog")
  this.model.bind('add', this.render, this);

},

addQuizDialog: function(event){
  console.log('addQuizDialog called')
  QuizMe.QuizCollection.create({display:"this is a display2",description:"this is a succinct description"});  
},

render: function() {
  console.log("render called")
},
});

QuizMe.App = new QuizMe.QuizView({model:QuizMe.Quiz})

});
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 5

你的问题是你绑定到模型:

this.model.bind('add', this.render, this);
Run Code Online (Sandbox Code Playgroud)

但是你要添加到一个集合中:

QuizMe.QuizCollection.create({
    display:     "this is a display2",
    description: "this is a succinct description"
});
Run Code Online (Sandbox Code Playgroud)

视图通常具有关联的集合或模型,但不能同时具有两者.如果您希望QuizView列出已知的测验,那么:

  1. 你可能应该称它为QuizListView类似的东西.
  2. 创建一个QuizView显示单个测验的新内容; 这个观点会有一个模型.
  3. 重做你QuizListView的工作与集合.

你应该得到这样的东西:

QuizMe.QuizListView = Backbone.View.extend({
    // ...
    initialize: function() {
        // You don't need to bind event handlers anymore, newer
        // Backbones use the right context by themselves.
        _.bindAll(this, 'render');
        this.collection.bind('add', this.render);
    },
    addQuizDialog: function(event) {
        this.collection.create({
            display:     "this is a display2",
            description: "this is a succinct description"
        });
    },
    render: function() {
        console.log("render called")
        // And some stuff in here to add QuizView instances to this.$el
        return this; // Your render() should always do this.
    }
});

QuizMe.App = new QuizMe.QuizView({ collection: QuizMe.QuizCollection });
Run Code Online (Sandbox Code Playgroud)

并观察后面的逗号render,较旧的IE会对此感到不安并导致难以追踪错误.

我会给你一个快速的演示,但http://jsfiddle.net/目前正在关闭.当它回来时,你可以从http://jsfiddle.net/ambiguous/RRXnK/开始玩游戏,那个小提琴已经设置了所有合适的Backbone东西(jQuery,Backbone和Underscore).