5

I have a requirement to "nag" a user about unsaved changes when they switch between different Backbone collection models (by clicking on a table row). I've googled for "check backbone model dirty data" (for instance) and not found anything definitive.

I accomplished this using underscore's "some" and isEqual functionality, in a manner such as the following, "some()" being sufficient to determine if there are any un-saved changes (as opposed to what those precise changes might be), in particular because the model attribute is actually an array of objects.

var anyDirty = _.some(myCollection.models, function(model) {
    return !_.isEqual(model.get('nodes'), model.previousAttributes()['nodes]);
});

I am new to Backbone and am wondering if this is an accepted sort of approach for adhoc checking for dirty model data. Or, does Backbone provide some sort of built in functionality for this purpose, that my initial attempts at googling did not reveal?

Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • 1
    What about http://stackoverflow.com/questions/9215036/backbone-js-is-there-a-change-since-last-server-save ? – nikoshr Aug 24 '13 at 07:36
  • Thanks for pointing that out. Now I'm realizing I didn't write my question specifically enough. I guess I want to know if *any* model in a particular collection has changed. In which case my use of _.some still seems to pertain, but inside of the iterator, I can use 'model.hasChanged()' instead of _.isEqual() – Dexygen Aug 24 '13 at 10:53
  • 1
    You can instead, listen to when `change` events fired. Persist it as a state on your collection. Clear it once collection has been sync back to server. Then only check from that state attribute. I think `change` is also fired when create a new model too so you may want to check for `isNew()` as well. – j03w Aug 25 '13 at 07:39
  • @j03w Thanks but persisting state means managing state and the more state there is to manage the higher the possibility of logic errors based on incorrect management of state -- state is evil and should be avoided if necessary – Dexygen Aug 25 '13 at 12:50

1 Answers1

2

I have another attribute I need to monitor in addition to 'nodes', so I'm switching to using changedAttributes(): http://backbonejs.org/#Model-changedAttributes:

var anyDirty = _.some(myCollection.models, function(model) {
    return model.changedAttributes();
});

What may make this an imperfect solution is that it seems like it will return an object of changedAttributes even if the attribute got changed back to it's original value. So it almost seems that what I need in the long run is to take a snapshot of the original data and compare against that. Still though, using model.changedAttributes() is a more concise alternative to what I first posted.

Dexygen
  • 12,287
  • 13
  • 80
  • 147