在Ember.js中扩展视图或使用mixin

Dun*_*ker 6 view object mixins ember.js

我想在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
});
Run Code Online (Sandbox Code Playgroud)

...或者,是否应该使用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
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

但是,如果使用mixin并扩展视图对视图有相同的影响我试图添加标准功能(也就是说,它们以相同的方式影响视图的对象和原型/实例),你看到了吗?使用一个优于另一个优势(无论是在效率,可维护性等方面)?

Kin*_*n2k 6

好问题,

简短,扩展视图.

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

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

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