Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing underscore.js to copy backbone.js Model attributes - algorithm
    text
    copied!<p>I want to copy all attributes from backbone.js Model object to another if they are not undefined. It's a little like a child overriding the attributes of a parent. There will be some attributes of the child object which should be excluded from the entire process. This is what I have so far:</p> <pre><code>function inherit(parent, child) { var childAttributes = Object.keys(child.attributes); // Don't involve these attributes in any way, they're special. attributes = _.without(attributes, ['specialCase1', 'specialCase2', 'specialCase3']); // This array will store undefined child attributes var undefChildAttributes = new Array(); for (i in attributes) { var attr = attributes[i]; // Get attribute name var value = child.get(attr); // ... and value var type = RealTypeOf(value); // ... and type if (type == 'undefined') { undefChildAttributes.push(attr); } } // Update the child attributes array to not include undefined any attributes attributes = _.without(attributes, undefChildAttributes); // Copy any attributes from child to parent // ------------------ PROBLEM AREA ------------------ for (var m=0; m&lt;attributes.length; m++) { var attr = attributes[m]; // Attribute to copy // I want to use _.extends in some way here, maybe like: _.extends(parent, child[attr]); } } </code></pre> <p>I'm stuck at the point of how to copy the attribute into the parent. The only way I have atm is a hack:</p> <pre><code>if (type == 'string') { eval('var o = {' + attr + ':"' + child.get(attr) + '"};'); } else { eval('var o = {' + attr + ':' + child.get(attr) + '};'); } parent.set(o); </code></pre>
 

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