我想说“当question_number
发生变化时,请运行updateQuestionNumber
。如果有任何异常question_number
(以及我提供自定义渲染功能的其他内容),请运行.render()” 。
以下代码的问题是updateQuestionNumber
和render
都会运行。
v.QuestionBuilder = Backbone.View.extend({
initialize: function() {
this.model.on('change:question_number', this.updateQuestionNumber, this);
this.model.on('change', this.render, this);
},
//only this function should run when question_number is changed
updateQuestionNumber: function(){
this.$('.question-number').text(this.model.get('question_number'));
},
//this should run when anything except question_number is changed
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.$el.fadeIn('slow');
/* blah blah blah */
return this;
}
});
答案 0 :(得分:0)
这是我能想到的最佳解决方案:
当this.render()触发时,我设置了一个不需要完整渲染的属性数组non_render(由this.model.on('change:whatever', this.whateverRenderFunction, this);
处理)。然后它检查changedAttributes。如果其中有任何内容不在non_render(._difference
)中,那么它会继续。否则它会返回。
这似乎是一个超级庞大的解决方案(我必须在initialize
和render
中维护non_render列表。任何改进都会很棒......
render: function(model, value, options){
if(model){ //this was triggered via .change()
var changed = _.keys(model.changedAttributes());
var non_render = ['question_number'];
//if there is anything in changed that's not part of non_render
if(_.difference(changed, non_render).length === 0){
return false;
}
}
var data = this.model.toJSON();
_.extend(data, _.result(this.templateProperties));
this.$el.html(this.template(data));
}
答案 1 :(得分:0)
initialize: function() {
this.model.on('change', function(model) {
var changed = model.getChanged();
if(changed && 1 === changed.length && changed.question_number) {
this.updateQuestionNumber();
} else {
this.render()
}
}, this);
},