Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for any dirty Backbone model data within collection

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?

like image 673
Dexygen Avatar asked Nov 01 '22 16:11

Dexygen


1 Answers

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.

like image 125
Dexygen Avatar answered Nov 09 '22 06:11

Dexygen