3

未定義でない場合、すべての属性を backbone.js Model オブジェクトから別のオブジェクトにコピーしたいと考えています。これは、親の属性をオーバーライドする子に少し似ています。プロセス全体から除外する必要がある子オブジェクトの属性がいくつかあります。これは私がこれまでに持っているものです:

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<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]);
   }
}

属性を親にコピーする方法に行き詰まっています。私がatmを持っている唯一の方法はハックです:

if (type == 'string') {
    eval('var o = {' + attr + ':"' + child.get(attr) + '"};');
 } else {
    eval('var o = {' + attr + ':' + child.get(attr) + '};');
}

parent.set(o);
4

1 に答える 1

5

eval角かっこ表記を使用すると、回避できます。

var o = {};
o[attr] = child.get(attr);
parent.set(o);

そして、私がそれを正しく理解した場合、あなたのコードに対する私の見解

function inherit(parent, child) {
    var attributes = child.toJSON(),
        keepkeys = _.keys(attributes);

    // remove special cases
    keepkeys = _.without(keepkeys, 'specialCase1', 'specialCase2');
    // or keepkeys = _.difference(keepkeys, ['specialCase1', 'specialCase2']);

    // remove undefined values
    keepkeys = _.filter(keepkeys, function (key) {
        return typeof(attributes[key])!=="undefined";
    });

    // with underscore>=1.3.3
    var result = _.pick(attributes, keepkeys);

    // with underscore<1.3.3
    // var result = {};
    // _.each(keepkeys, function (key) {
    //    result[key] = attributes[key];
    // });

    parent.set(result);
}

var P = new Backbone.Model();
var C = new Backbone.Model({
    copy1: "c1", 
    specialCase1: "do not copy", 
    undefkey: undefined
});

inherit(P, C);
console.log(P.toJSON());

そしてフィドルhttp://jsfiddle.net/tdCEF/

于 2012-04-28T10:40:58.167 に答える