【问题标题】:Multiple Mixins with same events in Ember.jsEmber.js 中具有相同事件的多个 Mixin
【发布时间】:2014-04-05 11:24:09
【问题描述】:

我想在 Ember.js 中的一个视图中包含多个 mixins,并且多个 mixins 和/或视图使用相同的事件(例如willInsertElement)。我正在运行 Ember 1.4.0-beta.5。

我知道每个 mixin 中的事件都会被视图覆盖。但是,我读过可以在 mixin 和视图中使用相同的事件挂钩,或者在同一视图中包含多个 mixin,方法是在 mixin 的上述事件方法的开头调用 this._super();。但是,我未能成功实现这一目标。因此,我的问题是,如何在视图和 mixin(或同一视图中包含的多个 mixin)中的同一事件挂钩中编写逻辑,以便调用每次事件挂钩中的所有逻辑。

这是一个例子:

App.StatsView = Em.View.extend(
    App.DateFormatting, {

    willInsertElement: function() {
        // Some view-specific logic I want to call here
    },
});

App.DateFormatting = Em.Mixin.create({

    willInsertElement: function() {
        this._super(); // This doesn't work.
        // Some mixin logic I want to call here
    },
});

注意这里的一种方法可能是不使用 mixin 而是扩展视图(因为 willInsertElement 是特定于 Em.View 的),但这在我们的应用程序中是不可维护的。

【问题讨论】:

    标签: javascript ember.js mixins superclass super


    【解决方案1】:

    如果您使用的不同函数不相互依赖,最好的解决方案是不要覆盖 willInsertElement 钩子,而是告诉函数在事件/钩子被调用时被引发。

    喜欢:

    App.StatsView = Em.View.extend(App.DateFormatting, {
      someSpecificFunction: function () {
        console.log('beer me');
      }.on('willInsertElement')
    });
    
    App.DateFormatting = Em.Mixin.create({
      dateFormattingFunction: function () {
        console.log('beer you');
      }.on('willInsertElement')
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2012-04-21
      • 2019-11-29
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多