【问题标题】:Extend a view or use a mixin in Ember.js在 Ember.js 中扩展视图或使用 mixin
【发布时间】:2013-12-24 02:35:24
【问题描述】:

我想在 Ember 应用程序的多个视图中包含标准功能。该功能包括将视图的 tagName 和 classNames 设置为相同以及跟踪每个视图的属性。

简而言之:我应该使用 mixin 还是扩展基本视图?

扩展问题...

是否应该扩展一个基本视图来做到这一点?例如:

App.BaseView = Em.View.extend({
    tagName: 'section',
    classNames: ['page_section', 'blue'],
    willInsertElement: function() {
        // Some functions called here that set properties
    },
});

App.PageOneView = App.BaseView.extend({
    // View specific stuff here
});

App.PageTwoView = App.BaseView.extend({
    // View specific stuff here
});

... 或者,是否应该使用 Mixin 来扩展功能?例如:

App.BaseMixin = Em.Mixin.create({
    tagName: 'section',
    classNames: ['page_section', 'blue'],
    willInsertElement: function() {
        // Some functions called here that set properties
    },
});

App.PageOneView = Em.View.extend(App.BaseMixin, {
    // View specific stuff here
});

App.PageTwoView = Em.View.extend(App.BaseMixin, {
    // View specific stuff here
});

我知道视图和 mixin 都是 Ember 对象,但是使用它们中的任何一个来将标准功能扩展到其他对象(例如视图)会影响对象和原型/实例(如果它们与对象不同)的交互方式以及是否在视图或视图对象的实例上设置属性?

如果上面的两个例子不同,设置 mixin 的 init 函数的属性会改变什么吗?例如:

App.BaseMixin = Em.Mixin.create({
    tagName: null,
    classNames: null,
    init: function() {
        this.set('tagName', 'section');
        // And so forth...
    },
});

但是,如果使用 mixin 和扩展视图对我尝试添加标准功能的视图具有相同的影响(也就是说,它们以相同的方式影响视图的对象和原型/实例),请执行您看到使用其中一种的优势(无论是在效率、可维护性等方面)吗?

【问题讨论】:

    标签: object view ember.js mixins


    【解决方案1】:

    好问题,

    短小精悍,扩展视图。

    1. 钩子/绑定是特定于视图的,因此不能将 mixin 应用于控制器、路由等,并且根据您的团队构成,您不希望给某人一个混合代码的机会那不属于。

    2. 在 Ember 中扩展一个类只是将基类变成一个 mixin 并将其应用于您的类。 https://github.com/emberjs/ember.js/blob/v1.2.0/packages/ember-runtime/lib/system/core_object.js#L488

    所以它几乎完全相同,只是你的基本视图更有意义,因为它只适用于视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多