在我的 Backbone.js 应用程序中,我有以下模型和 View :
var Operation = Backbone.Model.extend({
defaults: function() {
return {
sign: '-',
value: '0000',
index: 0
}
}
});
var operation = new Operation();
var OperationView = Backbone.View.extend({
el: '#operation',
initialize: function() {
this.listenTo(this.model, 'change:sign change:value', this.renderOperation);
this.renderOperation();
},
renderOperation: function() {
console.log('rendered once');
this.$el.html(this.model.get('sign') + this.model.get('value'));
}
});
var operationView = new OperationView({ model: operation });
View 监视的地方
'change:sign change:value'
(...每当“符号”或“值”发生变化时更新 View 。)
当我使用
// Test
setInterval(function() {
var newValue = parseInt(operation.get('value'), 10);
newValue += 500;
newValue += '';
operation.set({ 'sign': '+', 'value': newValue });
}, 1000);
...第一次执行 setInterval 时, View 更新两次(“渲染一次”在控制台记录 2 次)。
但是,由于我“同时”设置符号和值,我宁愿我的 View 只更新一次。
问题:在 Backbone.js 中,是否有任何方法可以 listenTo() 更改模型的多个(特定)属性,并且如果同时设置多个属性,则只渲染 View 一次?
最佳答案
您的 View 正在监听 'change:sign change:value',
因此,只要该属性发生变化,事件就会针对每个属性变化触发一次。
您始终可以在模型上收听 change
事件。如果同一集合哈希中的模型属性发生更改,这将仅触发一次更改
。
this.listenTo(this.model, 'change', this.renderOperation);
但是如果你仍然想监听属性上的多个更改事件并且只触发一次事件。您可能会诉诸黑客在设置值时传递 {silent: true}
并触发属性更改事件。这有点老套。
var Operation = Backbone.Model.extend({
defaults: function () {
return {
sign: '-',
value: '0000',
index: 0
}
}
});
var operation = new Operation();
var OperationView = Backbone.View.extend({
el: '#operation',
initialize: function () {
this.listenTo(this.model, 'change:sign change:value', this.renderOperation);
this.renderOperation();
},
renderOperation: function () {
console.log('rendered once');
this.$el.html(this.model.get('sign') + this.model.get('value'));
}
});
var operationView = new OperationView({
model: operation
});
setInterval(function() {
var newValue = parseInt(operation.get('value'), 10);
newValue += 500;
newValue += '';
operation.set({ 'sign': '+', 'value': newValue }, {silent: true});
operation.trigger('change:sign')
}, 1000);
关于javascript - 在 "simultaneous"属性更改时渲染一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18137381/