我有一个名为Pannel的 View ,它只是一个带有关闭按钮的背景。我想将该 View 扩展为一种称为PannelAdvanced的 View 。我将如何使用ribs.js做到这一点?

现在,所有示例都具有Backbone.View.Extend,但是仅扩展了Backbone.View;我想扩展PannelView

最佳答案

继承 View 的最简单方法是执行其他人已经在注释中建议的操作:

var Pannel = Backbone.View.extend({
});

var PannelAdvanced = Pannel.extend({
});

但是就像您在注释中指出的那样,如果您在Pannel中有一个initialize方法,那么如果您在PannelAdvanced中也有一个initialize方法,则不会调用它,因此您必须显式调用Pannel的initialize方法:
var Pannel = Backbone.View.extend({
   initialize: function(options){
      console.log('Pannel initialized');
      this.foo = 'bar';
   }
});

var PannelAdvanced = Pannel.extend({
   initialize: function(options){
      Pannel.prototype.initialize.apply(this, [options])
      console.log('PannelAdvanced initialized');
      console.log(this.foo); // Log: bar
   }
});

这有点丑陋,因为如果您有很多从Pannel继承的View,则必须记住要从所有View调用Pannel的初始化。更糟糕的是,如果Pannel现在没有初始化方法,但是您选择将来添加它,那么将来您将需要进入所有继承的类,并确保它们调用Pannel的Initialize。因此,这是定义Pannel的另一种方法,这样您继承的 View 就无需调用Pannel的initialize方法:
var Pannel = function (options) {

    // put all of Panel's initialization code here
    console.log('Pannel initialized');
    this.foo = 'bar';

    Backbone.View.apply(this, [options]);
};

_.extend(Pannel.prototype, Backbone.View.prototype, {

    // put all of Panel's methods here. For example:
    sayHi: function () {
        console.log('hello from Pannel');
    }
});

Pannel.extend = Backbone.View.extend;


// other classes inherit from Panel like this:
var PannelAdvanced = Pannel.extend({

    initialize: function (options) {
        console.log('PannelAdvanced initialized');
        console.log(this.foo);
    }
});

var pannelAdvanced = new PannelAdvanced(); //Log: Pannel initialized, PannelAdvanced initialized, bar
pannelAdvanced.sayHi(); // Log: hello from Pannel

关于inheritance - Backbone.js View 继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7735133/

10-09 23:43