创建主干插件

Creating a backbone plugin

本文关键字:插件 创建      更新时间:2023-09-26

试图创建一个从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: The Good Parts》一书:

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()内:

    未捕获的类型错误:Function.prototype.toString 不是通用的。

我正在尝试以主干库Marionette创建新版本视图的方式创建一个新插件。看起来我误解了应该这样做的方式。

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

你扩展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'});

另一方面,Crockford的Object.create填充被认为是过时的,因为(我相信)Object.create最近的实现需要不止一个参数。此外,您正在使用的特定函数不会遵从本机Object.create函数(如果存在),尽管您可能刚刚省略了应包装该函数的 if (typeof Object.create !== 'function') 语句。