在Backbone.js的我怎样才能型号超默认作为默认值子? [英] In Backbone.js how can I get Model superclass defaults to act as defaults for subclasses?

查看:124
本文介绍了在Backbone.js的我怎样才能型号超默认作为默认值子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,定义了一些默认值,并定义了一些默认的子类。但是,当我创建了子类的实例只着眼于当地的默认设置,不与母公司合并其默认值。有没有简单的方法来做到这一点没有在每个子类中的初始化函数父默认明确合并当地的默认值?

  VAR库存= Backbone.Model.extend({
    默认值:{
        猫:3,
        狗:5
    }
});VAR ExtendedInventory = Inventory.extend({
    默认值:{
        兔:25
    }
});变种EI =新ExtendedInventory({});
的console.log(ei.attributes);

此输出:

  {兔:25}

不是我想要的:

  {猫:3,狗:5,兔:25}


解决方案

您不能那样做。您将有子类都要做一遍

  _延伸(ExtendedInventory.prototype.defaults,{兔:25});

您的模型定义后,将这个。

I have a class that defines some defaults, and a subclass that defines some defaults. But when I create an instance of the subclass it only looks at the local defaults and does not merge its defaults with those of the parent. Is there any simple way to do this without explicitly merging the local defaults with the parent defaults in the initialize function of every subclass?

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

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

var ei = new ExtendedInventory({});
console.log(ei.attributes);

This outputs:

{rabbit: 25}

Not what I want:

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

解决方案

You can't do it like that. You will have to do it after the subclass

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

Put this after your model definition.

这篇关于在Backbone.js的我怎样才能型号超默认作为默认值子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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