Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js: Model event that fires when setting attributes to existing values?

In backbone.js, I'm noticing that the change and all events on a Model do not fire if you set the Model's attributes to its existing attributes.

For example, if I set up the following events:

 ActiveUser.bind('change', this.displayActiveUser, this);
 ActiveUser.bind('all', this.displayActiveUserAll, this);

And then I manually set the value of ActiveUser to the empty string:

ActiveUser.set({ text : '' });

The events fire if and only if ActiveUser.text is not already set to the empty string.

This is reasonable behaviour. However, is there an event I can use that will fire even if the value being set is the existing value?

Update: I don't see anything in the official Backbone.js list of events. Hmm.

like image 413
Richard Avatar asked Mar 27 '12 16:03

Richard


People also ask

How can we get the attribute value of a model in Backbone js?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

Which function has to be used when you want to trigger the event only once before being removed?

js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.

How does Backbone js work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


2 Answers

You can always trigger the change event manually with ActiveUser.trigger('change');.

like image 169
abraham Avatar answered Oct 05 '22 12:10

abraham


Trigger change event manually as abraham said

MyModel.trigger('change')

So its possible to trigger change event manually but it will not work well in some cases. Consider the case when your render method takes properties from model and your model is empty initially, so if your code sets something on model and straight after that line you say MyView.render() or MyModel.trigger('change') then what happens your render method might be faster and will not even take newly set properties.

Quick hacky alternative could be each time you set something, generate random number along and pass it to model:

MyModel.set({myProperty:something,rand:Math.random()});

or

MyModel.set({myProperty:something,t:(new Date).getTime()});

So in this case you are sure that model will always fire change event just because something changes, but it is hacky and if you have a lot going on then your app will become random number calculator.

Alternatively go with Peter Lyons method.

like image 39
Ivar Avatar answered Oct 05 '22 13:10

Ivar