Backbone.js。正确制作更改事件

Backbone.js. Make change event correctly

我正在使用 Backbone.js

编写 Todo 应用程序

您可以在下面看到我的部分代码。 型号:

 var Todo = Backbone.Model.extend({
    defaults : {
        title: 'Task Title',
        complete: false
    },
    initialize: function(){
        this.on("change:complete", function () {
            alert("foo");
        });
    }
});

查看:

var AppView = Backbone.View.extend({
        collection: todoCollection,
        el: 'body',
        events: {
            'click #tasks li .complete-task' : 'toggleComplete'
        }
        toggleComplete: function (e) {
            var modelCid = $(e.target).parent('li').attr('id');

             if ( this.collection.get(modelCid)['complete'] ){
                this.collection.get(modelCid)['complete'] = false;
             } else {
                 this.collection.get(modelCid)['complete'] = true;
             };
        }
    });

但是模型中的一些错误和更改事件不起作用。我不明白我哪里有错误。 请帮帮我。 10q.

根据 Backbone Documentation:

设置model.set(attributes, [options])

Set a hash of attributes (one or many) on the model. If any of the attributes change the model's state, a "change" event will be triggered on the model. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content. You may also pass individual keys and values.

因此您需要在模型上使用 set 方法来触发这些事件。所以你需要使用这样的东西:

this.collection.get(modelCid).set('complete',false);