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
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With