開始學習Backbone JS。閱讀Codeschool文檔。我只是不明白爲什麼我們需要在initialize中聲明this.model.on('....')
,而不是在toggleStatus
函數中只使用'this.render();'
。請有人解釋清楚。爲什麼我們不能在togglestatus函數中聲明this.render?
下面是代碼從我的文檔複製粘貼:
前:
var TodoView = Backbone.View.extend({
events: {
'change input': 'toggleStatus'
},
toggleStatus: function(){
this.model.toggleStatus();
this.render(); //Doesn’t work for other model changes , WHY IT DOESN'T WORK??
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
}
});
後:
var TodoView = Backbone.View.extend({
events: {
'change input': 'toggleStatus'
},
initialize: function(){
this.model.on('change', this.render, this);
},
toggleStatus: function(){
this.model.toggleStatus();
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});