Backbone listenTo 多个属性触发多个事件

Backbone listenTo multiple attributes firing multiple events

我有一个 Model,在 initialize 函数中我有以下代码:

this.listenTo(this, 'change:re change:read', this.patch);

补丁函数如下所示:

patch: function(object) {
  this.save(object.changed, { patch: true });
},

在我申请的其他地方,我可能 运行:

model.set({ re: 1 });

或:

model.set({ read: new Date() });

两者都可以正常工作,但是当我调用时:

model.set({ re: 1, read: new Date() });

patch 函数被调用两次,并且有两次往返服务器。如果可能的话,我想将其减少到一次往返。

谁能帮忙解决这个问题?

非常感谢

大卫

您的 patch 方法在 'change:re' 事件中被调用一次,在 'change:read' 事件中被调用一次。 Backbone 并不知道你真正的意思是 "tell me if at least one of re or read changes",它只知道你想在 re 变化时被告知,并且在 read 变化时被告知。

您可以侦听 'change' 事件并使用 changed 散列自行进行过滤:

changed model.changed

The changed property is the internal hash containing all the attributes that have changed since the last set.

像这样:

this.listenTo(this, 'change', this.patch);

然后:

patch: function() {
  if('re' in this.changed || 'read' in this.changed)
    this.save(this.changed, { patch: true });
}

演示:https://jsfiddle.net/ambiguous/ja20z021/

您可以使用 _.debounce 去除补丁函数,如下所示:

this.listenTo(this, 'change:re change:read', this.patch);

然后:

patch: _.debounce(function(object){
    this.save(object.changed, { patch: true });
},100)

“100”以毫秒为单位,您的函数在调用 save() 之前等待的时间。在此期间,可能会发生任意数量的更改事件,但只会调用一次保存。