4

下面我提供了一个我“认为”应该起作用的例子,但没有。我的期望是,如果一个控制器继承自另一个控制器,那么它应该能够访问父类中提供的行为。我知道“需要”可以实现相同的行为,但我认为如果你可以继承行为会更清晰。

https://gist.github.com/4589210

4

2 回答 2

5

您也可以使用mixin. 这是什么?这是一种多继承。

App.Important = Ember.Mixin.create({
  sharedBehavior: function() {
    return "A winner is you!!!";
  }.property()
});

App.OtherImportant = Ember.Mixin.create({
  otherSharedBehavior: function() {
    return "A winner is not you!!!";
  }.property()
});

App.AnotherController = Ember.controller.extend(App.Important, App.OtherImportant, {
  importantStuff: function() {
    var ohBeehave = this.get("sharedBehavior");
    if(ohBeehave) { 
      return ohBeehave;
    } else {
      return "FML";
    }
  }.property("sharedBehavior")
});

http://emberjs.com/api/classes/Ember.Mixin.html

于 2014-11-10T17:22:29.700 回答
2

您是正确的,控制器应该能够从其他控制器继承属性。这是一个基于您的要点的工作示例:

http://jsbin.com/uzeyum/1/edit

App = Ember.Application.create();

App.ApplicationController = Ember.Controller.extend({
  sharedBehavior: function() {
    return "A winner is you!!!";
  }.property()
});


App.AnotherController = App.ApplicationController.extend({
  importantStuff: function() {
    var ohBeehave = this.get("sharedBehavior");
    if(ohBeehave) { 
      return ohBeehave;
    } else {
      return "FML";
    }
  }.property("sharedBehavior")
});

也就是说,根据经验,我可以告诉你,继承很少是你想要的。造成这种情况的原因有很多,请参阅更喜欢组合而不是继承?详情。

通过通过needs属性而不是继承声明一组依赖项,随着时间的推移,您会发​​现您的应用程序不那么脆弱并且更容易测试/更改。

于 2013-01-21T21:45:26.623 回答