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

前端之家收集整理的这篇文章主要介绍了ember.js – ember中.create()和.createWithMixins()之间的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
.create()和.createWithMixins()之间有什么区别?我无法找到有关这方面的任何文件.当我使用.create()创建一个视图实例,并在didInsertElement方法调用this._super(),然后抛出以下错误

Ember.Object.create no longer supports defining methods that call
_super.

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

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

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

解决方法

Wikipedia

In object-oriented programming languages,a mixin is a class,which
contains a combination of methods from other classes. How such
combination is done depends on language,but it is not by inheritance.
If a combination contains all methods of combined classes it is
equivalent to multiple inheritance.

在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'
})

另一方面,crateWithMixins允许您将另一个类定义混合到单个对象实例或另一个类中.所以让我们说上面有一样的SomeClass,但是你不想通过扩展来创建另一个类.在这种情况下,您可以使用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'
});

但是,如果要使用Mixin创建一个新类,可以扩展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();

查看API Documentation以及JSFiddle.

编辑:对于_super(),只有在创建一个新类(通过扩展)时才使用这个.当您创建现有类的实例时,不应调用_super().

另一件事.我看到你正在尝试直接创建一个视图.我相信,根据您的代码,您应该扩展Ember.View,让框架在适当的时候为您创建实例.如果您手动创建,那么您将对其工作流程的某些部分负责,例如将其附加到DOM,删除它等.也许我看不到整个图片,但是基于这个代码,我认为你不应该调用create there并调用extend,然后你可以调用_super()

原文链接:https://www.f2er.com/js/154498.html

猜你在找的JavaScript相关文章