【问题标题】:How would one extend multiple mixins when creating a new mixin in Ember.js在 Ember.js 中创建新的 mixin 时如何扩展多个 mixin
【发布时间】:2014-09-30 21:44:53
【问题描述】:

我之前发现在创建新的 mixin 时可以扩展 mixin,如下所示:

App.SomeNewMixin = Ember.Mixin.create(App.SomeOldMixin, {
  someMethod: function() { return true; }
});

现在我正在尝试使用两个现有的 mixin,但似乎 Mixin.create 只支持 2 个参数。

App.SomeNewMixin = Ember.Mixin.create(App.SomeOldMixinOne, App.SomeOldMixinTwo, {
  someMethod: function() { // No access to methods defined in SomeOldMixinOne }
});

这似乎是 Ember Mixins 的一个严重限制。 Ember 文档几乎没有涵盖 Ember.Mixin,所以我不确定如何继续。我已经尝试在 SomeNewMixin 的 init 函数中使用 Ember.Mixin.apply,也无济于事。

App.SomeNewMixin = Ember.Mixin.create({
  init: function() {
    this._super();
    this.apply(App.SomeOldMixinOne);
    this.apply(App.SomeOldMixinTwo);
  }

  someMethod: function() { return true; }
});

任何关于可能解决方案的见解将不胜感激!

【问题讨论】:

    标签: ember.js mixins


    【解决方案1】:

    创建一个扩展多个其他 mixin 的 mixin 应该可以正常工作。

    例如看这个:

    var App = Ember.Application.create();
    
    App.SomeOldMixin = Ember.Mixin.create({
      someOldMethod: function() { return 'old'; },
      someOldMethod2: function() { return 'old2'; }
    });
    
    App.SomeNewMixin = Ember.Mixin.create({
      someNewMethod: function() { return 'new'; }
    });
    
    App.SomeNewerMixin = Ember.Mixin.create({
      someNewerMethod: function() { return 'newer'; }
    });
    
    App.SomeNewestMixin = Ember.Mixin.create(App.SomeOldMixin, App.SomeNewMixin, App.SomeNewerMixin, {
      someOldMethod: function() { 
        return this._super() + ' ' + this.someOldMethod2(); 
      },
      someNewestMethod: function() { return 'newest'; }
    });
    
    App.ApplicationController = Ember.Controller.extend(App.SomeNewestMixin, {
      test: function() {
        console.log(this.someOldMethod());
        console.log(this.someNewMethod());
        console.log(this.someNewerMethod());
        console.log(this.someNewestMethod());
      }.on('init')
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2014-10-30
      • 2014-05-11
      • 2018-05-06
      • 2012-02-23
      相关资源
      最近更新 更多