我正在使用 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。
最佳答案
根据主干 Documentation :
设置 model.set(属性,[选项])
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);
关于javascript - Backbone .js。正确设置更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28125772/