将model.set与Backbone Associations一起使用时合并属性

时间:2014-11-23 06:29:04

标签: javascript backbone.js backbone-associations

我的问题非常特定于Backbone Associations(http://dhruvaray.github.io/backbone-associations)。我想知道在嵌套模型上设置属性时是否可以合并属性。这是一个减少问题的方法:

// define the Layout model
var Layout = Backbone.AssociatedModel.extend();

// define the User model, with layout as a Related model
var User = Backbone.AssociatedModel.extend({
    relations: [
        {
            type: Backbone.One,
            key: 'layout',
            relatedModel: Layout
        }
    ],
    defaults: {
        layout: {}
    }
});

// create a new user
var user = new User({ user_name: 'pascalpp' });

// set a property on the layout model
user.set('layout.foo', 'bar');
user.get('layout.foo'); // returns 'bar'

// call set on the user directly, passing a JSON structure with no foo property
user.set({ layout: { 'baz': 'bing' } });
user.get('layout.foo'); // foo got wiped, so this returns undefined

我面临的真实场景是,我们需要为用户获取部分数据并在用户模型上设置该部分数据,而不会删除当前提取中不存在的先前设置的属性。所以我希望我们可以在设置属性时合并。这可能吗?

1 个答案:

答案 0 :(得分:2)

如果新模型和现有模型的id匹配,则Backbone-associations会更新现有的嵌套模型。如果id未定义或不匹配,则嵌套模型将被新模型替换。

我为这些单例嵌套模型做的是我介绍假id = 0然后它就像预期的那样工作。

这是一个有效的jsfiddle

工作代码:

// define the Layout model
var Layout = Backbone.AssociatedModel.extend({
    defaults: {
        id: 0    
    }
});

// define the User model, with layout as a Related model
var User = Backbone.AssociatedModel.extend({
    relations: [
        {
            type: Backbone.One,
            key: 'layout',
            relatedModel: Layout
        }
    ],
    defaults: {
        layout: {}
    }
});

// create a new user
var user = new User({ user_name: 'pascalpp' });

// set a property on the layout model
user.set('layout.foo', 'bar');
user.get('layout.foo'); // returns 'bar'

// call set on the user directly, passing a JSON structure with no foo property
user.set({ layout: { id:0, 'baz': 'bing' } });
user.get('layout.foo'); // foo got wiped, so this returns undefined

alert(user.get('layout.foo'))