2012-08-17 47 views
4

试图创建一个从Backbone.Model“继承”但重写sync方法的骨干“插件”。创建骨干插件

这是我到目前为止有:

Backbone.New_Plugin = {}; 
Backbone.New_Plugin.Model = Object.create(Backbone.Model); 
Backbone.New_Plugin.Model.sync = function(method, model, options){ 
    alert('Body of sync method'); 
} 

的方法:Object.create()直接从书的Javascript采取:好的部分

Object.create = function(o){ 
    var F = function(){}; 
    F.prototype = o; 
    return new F(); 
}; 

我越来越尝试使用新型号时出现错误:

var NewModel = Backbone.New_Plugin.Model.extend({}); 
// Error occurs inside backbone when this line is executed attempting to create a 
// 'Model' instance using the new plugin: 
var newModelInstance = new NewModel({_pk: 'primary_key'}); 

错误发生在Backbone 0.9.2开发版本的第1392行。功能inherits()内:

 
    Uncaught TypeError: Function.prototype.toString is not generic . 

我试图创建的骨干库Marionette创建视图的新版本的方式一个新的插件。 IT看起来像是误解了应该这样做的方式。

什么是创建骨干插件的好方法?

回答

6

你延伸的方式Backbone.Model不是你想要去做的。如果你想创建一个新的类型的模型,只需使用extend

Backbone.New_Plugin.Model = Backbone.Model.extend({ 
    sync: function(method, model, options){ 
     alert('Body of sync method'); 
    } 
}); 

var newModel = Backbone.New_Plugin.Model.extend({ 
    // custom properties here 
}); 

var newModelInstance = new newModel({_pk: 'primary_key'}); 

在另一方面,克罗克福德的Object.create填充工具被认为是过时的,因为(我相信)更近的Object.create实现需要多个参数。此外,您使用的特定功能不会推迟到原生Object.create函数,如果它存在,但您可能刚刚省略了应包装该函数的if (typeof Object.create !== 'function')语句。

+0

啊优秀,非常感谢!是的,我确实忽略了Object.create函数包装器,因为我想将帖子中的代码减少到最小。我工作的版本确实有封装。 – 2012-08-17 22:18:57