Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Backbone model hasChanged() always return false?

Given the following snippet:

var m = new Backbone.Model({
    name: 'joshua'
});

m.set('name', 'something else');

If I now call m.hasChanged() or m.hasChanged('name') I get false. Why? My understanding is that both of these should return true.

m.changedAttributes() also returns false.

Here is a fiddle that illustrates what I'm doing, and expecting: http://jsfiddle.net/9cvVv/88/

EDIT: It seems that unless you pass { silent: true; } to the set() method then it will fire the change event on your model which clears out the changedAttributes(), etc. Essentially these properties only track changes since the last time the change event was triggered.

I read that in the documentation but didn't really understand it at first.

This doesn't seem very useful to me. I would appreciate any explanation of why this works the way it does and the best way to achieve the result I want. (Passing around {silent: true; } and giving up usage of the change event seems like a waste.)

like image 304
joshuapoehls Avatar asked Mar 27 '12 15:03

joshuapoehls


People also ask

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.

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)

Why use Backbone JS?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is Backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

Unless you pass { silent: true; } to the set() method then it will fire the change event on your model which clears out the changedAttributes(), etc. Essentially these properties only track changes since the last time the change event was triggered.

So the answer is to call this instead:

m.set('name', 'something else', {silent: true})
like image 133
joshuapoehls Avatar answered Oct 21 '22 11:10

joshuapoehls