Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone listenTo multiple attributes firing multiple events

I have a Model which in the initialize function I have the following code:

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

The patch function looks like this:

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

Elsewhere in my application I may run:

model.set({ re: 1 });

or:

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

both of which work perfectly, however when I call:

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

The patch function gets called twice and there are two round trips to the server. I would like to keep this down to one round trip if possible.

Can anyone help with this one?

Many thanks

David

like image 275
David Avatar asked Feb 24 '15 22:02

David


2 Answers

Your patch method gets called once for the 'change:re' event and again for the 'change:read' event. Backbone doesn't know that you really mean "tell me if at least one of re or read changes", it just knows that you want to be told if re changes and told if read changes.

You could listen for 'change' events and do the filtering yourself using the changed hash:

changed model.changed

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

Something like this:

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

and then:

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

Demo: https://jsfiddle.net/ambiguous/ja20z021/

like image 153
mu is too short Avatar answered Sep 22 '22 17:09

mu is too short


You can debouce the patch function using _.debounce, like so:

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

and then:

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

The "100" is in milliseconds, the time your function waits before calling save(). In that time period, any number of change events can happen but the save is called only once.

like image 42
IlangoRajagopal Avatar answered Sep 23 '22 17:09

IlangoRajagopal