我知道 JS 的设计目的并不是“干净地”处理每个 OOP 的继承,但我想知道 Ember 是否有办法实现这一点。
在 Ember 中,我认为 Ember.ObjectController.extend({...});
是某种继承,但不完全 - 我们当然可以添加自己的属性和方法,因此函数.extend({...})
,但是我们不能“覆盖”已经存在的函数。我想知道是否有这样的解决方法。
如果我创建了一个基本 Controller ,我将如何定义我希望子 Controller 实现的功能?我有基本 Controller (仅理论代码):
App.BaseController = Ember.ObjectController.extend({
// Methods meant for a child controller to implement
abstractMethod1: null,
abstractMethod2: null,
virtualMethod1: function(){
...
},
actions: {
execute: function(){
if(this.get("abstractMethod1"))
this.get("abstractMethod1")();
...
if(this.get("abstractMethod2")
var x = this.get("abstractMethod2")();
}
}
});
然后我有一个执行 Controller 尝试覆盖这些函数:
App.ImplementingController = App.BaseController.extend({
/* How would I implement abstractMethod1 and abstractMethod2 here!?
For virtualMethod1, how would I call something like base.virtualMethod1()
or super.virtualMethod1()?
*/
});
我发现自己创建了大量具有基本相同代码的 Controller ,除了模型名称及其属性之外。如果能够在 Ember 中实现这个计划那就太好了。该怎么办?
最佳答案
实际上,Ember 做得非常好,你只需不覆盖它,它就会触及基本实现。或者你重写它,它会破坏基本实现。 (这本质上也是 Mixins 的工作方式, http://emberjs.com/api/classes/Ember.Mixin.html )如果你想访问一个 base
函数、属性等,只需用它来访问它(它本质上将两个类粉碎在一起,给予优先级到扩展类。
基础
App.BaseController = Ember.ObjectController.extend({
a:'Base',
b:'Base',
acomp: function(){
return 'Base';
}.property(),
bcomp: function(){
return 'Base';
}.property(),
e:function(){
return 'Base';
},
f:function(){
return 'Base';
}
});
扩展
App.IndexController = App.BaseController.extend({
b:'Index',
c:'Index',
bcomp: function(){
return 'Index';
}.property(),
f:function(){
return 'Index';
},
actions:{
foo:function(){
console.log(this.e());
console.log(this.f());
}
}
});
Ember 组合它们后的样子
App.IndexController....
a:'Base'
b:'Index',
c:'Index',
acomp: function(){
return 'Base';
}.property(),
bcomp: function(){
return 'Index';
}.property(),
e:function(){
return 'Base';
},
f:function(){
return 'Index';
},
actions:{
foo:function(){
console.log(this.e());
console.log(this.f());
}
}
});
关于javascript - Ember Controller 和 "virtual"和/或 "abstract"方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187147/