Note that there are some explanatory texts on larger screens.

plurals
  1. PODeep Cloning Backbone.js Models
    text
    copied!<p>I am working in jquery with backbone.js and running into the case where i need to duplicate models, but i need to do a deep copy on them so no references exist between the copies. Models can have other models as attributes. Models can have anon functions as attributes.</p> <p>So i'm working on creating an algorithm that will deep clone most backbone models. I’m expecting that all bindings should be removed (for the new instance) during this copy so I’m not worried about trying to keep them.</p> <p>Goals:</p> <ul> <li>Able to duplicate all simple variable (String, Int, float, etc) and store it into the new model, as the same name. <ul> <li>Done, using toJSON to create a new JSON object which can be passed to set(). This object only contains simple attributes, i.e. does not include attributes assigned to functions or other models. </li> </ul></li> <li>Able to duplicate the anon functions some variables will be assigned to, without knowing function/attribute names beforehand. <ul> <li>If I know the name of the attribute which is assigned to a function I can copy it. But if the model is new or unknown I don’t have that information.</li> </ul></li> <li>If an attribute is another backbone model, call the deep copy algorithm recursively on that attribute. <ul> <li>Not able to check if an attribute is a backbone model with native backbone methods, looking for a work around.</li> </ul></li> </ul> <p>The simplified version of what I currently have is below:</p> <pre> /** * Performs a deep copy of a backbone.js model * All bindings for the copy are lost * @param orgModel - the original model to copy */ function deepCopyModel(orgModel) { var dupModel = Backbone.Model.extend({}); var orgAttributes= orgModel.toJSON(); var keepAttr=_.keys(orgAttributes); //remove any special cases keepAttr=_.without( keepAttr , 'specialCase1', 'specialCase2' ); //or keepAttr=_.difference(keepAttr, ['specialCase1', 'specialCase2'] ); //remove undefined values keepAttr=_.filter(keepAttr,function(key) { return ( typeof(attributes[key])!="undefined" ); }); //grab the resulting list of attributes after filtering var result=_.pick(attributes,keepAttr); //assign attributes to the copy using set dupModel.set(result); //TODO: Implement deep copy of functions //TODO: Implement deep copy of inner models return dupModel; } </pre> <p>Any help or insight you can give would be greatly appreciated. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload