“渲染一次”;同时“;属性更改

Render once on "simultaneous" attribute change

本文关键字:同时 属性 渲染一次 一次      更新时间:2023-09-26

在我的Backbone.js应用程序中,我有以下模型和视图:

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 });

视图监视的位置

'change:sign change:value'

(…每当"符号"或"值"发生变化时更新视图。)

当我使用时

// Test
setInterval(function() {
    var newValue = parseInt(operation.get('value'), 10);
    newValue += 500;
    newValue += '';
    operation.set({ 'sign': '+', 'value': newValue });
}, 1000);

第一次执行setInterval时,视图会更新两次("rendered once"为console.log两次)。

然而,由于我"同时"设置符号和值,我宁愿我的视图只更新一次。

问题:在Backbone.js中,是否有任何方法可以列出模型的多个(特定)属性中的更改,并且如果同时设置了多个属性,则只渲染视图一次

您的视图正在侦听两个'change:sign change:value',

因此,当该属性发生更改时,每个属性更改都会触发一次事件。

您可以始终侦听模型上的change事件。如果模型属性在同一集合散列中改变,则其将仅触发单个CCD_。

this.listenTo(this.model, 'change', this.renderOperation);

检查Fiddle-更改事件

但是,如果您仍然想侦听属性上的多个更改事件,并且只触发一次事件。您可能会在设置值时使用破解方法传递{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);

抑制事件并触发Fiddle