ember中.create()和.createWithMixins()之间的区别

phk*_*tha 9 handlebars.js ember.js

.create()和之间有什么区别.createWithMixins()?我无法找到任何有关此问题的文件.当我使用方法创建视图实例.create()this._super()didInsertElement方法中调用时,抛出以下错误:

Ember.Object.create不再支持定义调用_super的方法.

但是,当我更换.create()使用.createWithMixins()一切正常.这是代码和示例js小提琴:

App.SampleView = Ember.View.create({
    sampleProperty : "a",
    didInsertElement : function(){
        this._super();
        this.set("sampleProperty", "b");        
    } 
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/bErRT/3/.

Mil*_*Joe 23

来自维基百科:

在面向对象的编程语言中,mixin是一个类,它包含来自其他类的方法的组合.如何完成这样的组合取决于语言,但它不是通过继承.如果组合包含组合类的所有方法,则它等同于多重继承.

在Ember中,对象的实例是create使用不带参数的方法创建的,或者使用表示该类型属性的单个散列(kvo)创建,它们将自动填充.例:

var SomeClass = Ember.Object.extend({
    name: '',
    url: ''
});

// this instance will have a "name" and a "url" properties with blank values
var someInstance = SomeClass.create();

// this instance will have the same properties, but now 
// their values will be populated
var anotherInstance = SomeClass.create({
    name: 'Ember.js',
    url: 'http://emberjs.com'
})
Run Code Online (Sandbox Code Playgroud)

另一方面,crateWithMixins允许您另一个类定义混合到单个对象实例或另一个类中.因此,假设您具有相同的内容SomeClass,但您不希望通过子类对其进行子类化extend并创建另一种类型.在这种情况下,您可以使用a Mixin来确保只有那个实例将具有这两个类的定义.例:

var SomeClass = Ember.Object.extend({
    name: '',
    url: ''
});

// note that you don't extend a mixin, you only create
var SomeOtherClass = Ember.Mixin.create({
    doSomething: function() {
        console.log('doing my thing');
    }
});

// This instance will have a method called "doSomething"
var x = SomeClass.createWithMixins(SomeOtherClass, { 
    name: 'Ember.js', 
    url: 'http://emberjs.com' 
});

// this instance only has methods/properties defined in "SomeClass"
// therefore, no method called "doSomething"
var y = SomeClass.create({ 
    name: 'Google', 
    url: 'http://google.ca'
});
Run Code Online (Sandbox Code Playgroud)

但是,如果要创建带有a的新类Mixin,可以将第一个参数作为第一个参数extend Em.Object传递Mixin,如下所示:

var AnotherClass = Ember.Object.extend(SomeOtherClass, {
    firstName: '',
    lastName: ''
});

var z = AnotherClass.create();
z.set('firstName', 'Hiro');
z.set('lastName', 'Nakamura');
z.doSomething();
Run Code Online (Sandbox Code Playgroud)

查看API文档以及此JSFiddle.

编辑:至于_super(),您只在创建新类(via extend)时使用它.当您create是现有类的实例时,不应该调用_super().

另一件事.我看你想create一个View直接.我相信,根据您的代码,您应该扩展Ember.View并让框架在适当的时候为您创建实例.如果手动创建,你会承担责任,其追加到DOM,删除它,等也许我看不到全貌其工作流程的某些部分,但仅根据这个代码,我想你应该打电话给create那里打电话extend,然后你就可以打电话了_super()