扩展视图时扩展行为

时间:2015-02-13 16:00:20

标签: marionette

任务是:
MyViewX使用BehaviorA和B
MyViewY扩展了MyViewX,
并使用MyViewX中的所有行为,以及BehaviorC

// The following code works
// 
var MyViewX = Marionette.ItemView.extend({
    behaviors: {
       BehaviorA: {},
       BehaviorB: {}
    }
});

var MyViewY = MyViewX.extend({
    behaviors: {
       BehaviorA: {},
       BehaviorB: {},
       BehaviorC: {}
    }
});

问题:如何利用X中的行为定义,以便在Y中我不需要重复A和B?

// this is not good.  It overrides X.  Y has only C
var MyViewY = MyX.extend({
    behaviors: {
       BehaviorC: {}
    }
});


// maybe something like this?
// but how exactly to get X's behaviors here?
var MyViewY = MyViewX.extend({
    behaviors: _.extend{
      BEHAVIORS_OF_THE_SUPER_OF_THE_CURRENT_CLASS,
      { BehaviorC: {} }
    }
});


// this gives no errors, 
// but A and B do not behave, as if they are not used.
//
var MyViewY = MyViewX.extend({
  behaviors: { BehaviorC: {} },
  initialize: function () {
      var b = this.behaviors;
      this.behaviors = _.extend( 
          MyViewY.__super__.behaviors,
          b
      );
  }
});

1 个答案:

答案 0 :(得分:2)

您可以通过访问MyViewX来获取prototype的行为。使用理想的解决方案,以下工作应该有效:

var MyViewY = MyViewX.extend({
  behaviors: _.extend({},
    MyViewX.prototype.behaviors,
    { BehaviorC: {} }
  );
});

最后一个示例不起作用的原因是因为Marionette Behaviors被添加到Marionette.View构造函数中的视图中,该构造函数发生在最后调用initialize的Backbone.View构造函数之前。