在 Backbone.js 中扩展模型超类的默认值 [英] Extending the defaults of a Model superclass in Backbone.js

查看:18
本文介绍了在 Backbone.js 中扩展模型超类的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向this 答案,但我似乎无法这样做,我深表歉意.

I would like to pose this as a question to this answer but I can't seem to do so, I apologize.

扩展子类的默认值反映在超类中.这似乎违背了目的,我更倾向于在子类中明确列出超类的默认值以获得我正在寻找的结构.

Extending the defaults for the subclass are reflected in the superclass. This seems to defeat the purpose and I'm more apt to explicitly list the superclass' defaults in the subclass to get the structure I'm looking for.

var Inventory = Backbone.Model.extend({
    defaults: {
        cat: 3,
        dog: 5
    }
});

var ExtendedInventory = Inventory.extend({
});

_.extend(ExtendedInventory.prototype.defaults, {rabbit: 25});

var i = new Inventory();
var ei = new ExtendedInventory();
console.log(i.attributes);
console.log(ei.attributes);

输出:

{cat: 3, dog: 5, rabbit: 25}
{cat: 3, dog: 5, rabbit: 25}

不是我(也不是,我假设,op) 想要:

Not what I (nor, I assume, the op) want:

{cat: 3, dog: 5}
{cat: 3, dog: 5, rabbit: 25}

推荐答案

问题是 Inventory.prototype.defaultsExtended.prototype.defaults 有相同的引用,因为您没有覆盖引用.

The problem is that Inventory.prototype.defaults and Extended.prototype.defaults has the same reference, because you have not override the reference.

所以你可以通过两种方式做到这一点,也许更多,但我只找到了这两种:

So you can do this in 2 ways, maybe more but i only found this 2:

第一个例子不正确(见评论);请参考第二个.

The first example is incorrect (see comments); please refer to the second.

var ExtendedInventory = Inventory.extend({
    defaults: {
        rabit:25
    }
});

_.extend(ExtendedInventory.prototype.defaults, Inventory.prototype.defaults);

var ExtendedInventory = Inventory.extend({
    defaults: _.extend({},Inventory.prototype.defaults,
         {rabit:25}
    )
});

我认为第一个看起来更干净.

I think the first looks cleaner.

这篇关于在 Backbone.js 中扩展模型超类的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆