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.
js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)
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.
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.
You can always trigger the change event manually with ActiveUser.trigger('change');
.
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.
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