gpt4 book ai didi

backbone.js - 使用underscore.js复制backbone.js模型属性-算法

转载 作者:行者123 更新时间:2023-12-01 11:52:16 25 4
gpt4 key购买 nike

我想将所有属性从 backbone.js 模型对象复制到另一个,如果它们不是未定义的话。这有点像 child 覆盖了 parent 的属性。子对象的一些属性应该从整个过程中排除。这是我目前所拥有的:

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

最佳答案

您可以使用括号表示法避免 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());

还有一把 fiddle http://jsfiddle.net/tdCEF/

关于backbone.js - 使用underscore.js复制backbone.js模型属性-算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10362390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com