2012-08-17 69 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