0

如何使用原型为模型的每个实例附加构造函数?创建 Backbone.Model 的实例时,我一直在尝试修改构造函数方法。但是我不想将构造函数方法附加到我单独创建的每个模型上。添加初始化作品的原型;唯一的问题是,如果初始化与模型一起传递,它会通过下划线扩展方法覆盖它。

我试过这个

Backbone.Model.prototype.constructor = function(attributes, opts) {
        console.log('hi');
        Backbone.Model.prototype.constructor.call(this, attributes);
};

唯一的问题是,它在扩展之外不起作用;只有当构造函数位于您在创建新实例时扩展模型的对象内时,它才会被调用。

我只需要在创建每个模型的实例时运行一些代码。我想使用节点的 socket.io 框架执行一些自动绑定工作。

4

1 回答 1

1

It's not recommended to mess with the internals of backbone inheritance and use the provided methods and flow to achieve model manipulation on initialization. To do that - in a similar fashion as with collections, views or routers you have an initialization method that you should override that takes the role of a constructor.

If you need to alter all your models just create a new base class that you will later use as a super class for all your models and then if you need to overwrite the initialization method of subclasses remeber to call the super class initializer using the built in backbone class __super__ property.

initialize: function() {
    this.constructor.__super__.initialize.call(this);
    // whatever
},

Altering the core of backbone will never do good for you in the long run as it my prevent you from being able to easily update to new version if they would introduce conflicting changes.

I've been there and done that - and after doing it I'd recommend not following this path to anybody!

于 2012-10-24T11:17:40.257 回答