Eusebiu Marcu
Eusebiu Marcu

Reputation: 320

Backbone.js - model set during change

I'd like to do model.set(...) during the "change" event - some model attributes must be in sync: e.g. I have a budged that can cover a number of products but if I change the budget, the number of products must be updated and vice-versa. I've tried disabling the "change" event (i.e. model.off('change');) and then enable it after model.set(...), i.e. model.on('change', callbackFunction); , but I the change event handler/callback is still called.

What is the best approach for updating the model in the changed handler/callback?

Upvotes: 0

Views: 61

Answers (2)

josephnvu
josephnvu

Reputation: 1242

You can control setting the model and be "silent" about it. So if you want to set something and make it NOT call change you need to add silent: true for example:

model.set('budget', '$12.34', { silent: true })

Also you can be specific on the change. So say one of your other models needs to listen to only the "budget total" for example. You just listen to the change of the budget total:

modelOne.listenTo( modelTwo, 'change:budgetTotal', function( modelTwo, value ){ 
  this.set('budgetTotal', value ); 
});

Upvotes: 1

Dmitriy
Dmitriy

Reputation: 340

You can pass options object with silent flag

this.model.set({someKey:25}, {silent: true});

There would be no change event

Upvotes: 2

Related Questions