我有一个简单的ObjectProxy,我想在easy(呃)上调用方法.例如,我计划"代理"的对象有一个名为foo和bar的方法 - 它们不会直接导致我做这样的事情.
this.get("model").get("content").foo();
this.get("model").get("content").bar();
Run Code Online (Sandbox Code Playgroud)
相反,我更喜欢foo和bar的行为就像它们在物体上一样
this.get("model").foo();
this.get("model").bar();
Run Code Online (Sandbox Code Playgroud)
我可以通过对ObjectProxy本身的foo和bar方法进行硬编码来实现这一点(长手) - 然后拉动内容并手动调用方法w /如此应用
return Ember.ObjectProxy.extend({
content: function() {
var filter_value = this.get("filter_value");
return this.get("source").filterBy("id", filter_value).objectAt(0);
}.property("source.[]"),
foo: function() {
var content = Ember.get(this, 'content');
return content["foo"].apply(content, arguments);
},
bar: function() {
var content = Ember.get(this, 'content');
return content["bar"].apply(content, arguments);
}
}).create({
filter_value: id,
source: store.find(type)
});
Run Code Online (Sandbox Code Playgroud)
相反,如果我想代理这样的每个"方法" - 我怎样才能以不会伤害ember已经建立的树的方式设置原型?
我不一定推荐这样做,但如果您不想总是定义函数,那么这是一个想法。说实话,向 ember 添加一些东西并不是一个糟糕的主意,我讨厌必须深入两层才能实现这些功能。
Ember.ObjectProxy.reopen({
addFunc: function (content, method) {
this[method] = function () {
if (!content[method]) return;
return content[method].apply(content, arguments);
};
},
setupMethods: Ember.observer('content', function () {
var content = this.get('content');
if (!content) return;
for (var item in content) {
if (typeof content[item] == "function") {
if (!this[item]) { // watch out for clashing names
this.addFunc(content, item);
}
}
}
})
});
Run Code Online (Sandbox Code Playgroud)
我认为跟踪添加的方法,并可能在内容更改后进行清理并不是一件可怕的事情,但我怀疑单个对象代理通常拥有多个底层对象。
var o = Ember.ObjectProxy.create();
console.log(o.foo);
o.set('content', {
foo: function(){
console.log('hello');
}
});
console.log(o.foo);
o.foo();
o.set('content',{
bar: function(){
console.log('bar');
}
});
o.bar();
Run Code Online (Sandbox Code Playgroud)
示例: http: //emberjs.jsbin.com/juwomezape/1/edit
需要注意的是,在定义内容之前,不存在任何方法,但通常我们在开始处理对象之前就已经解析了对象。
| 归档时间: |
|
| 查看次数: |
648 次 |
| 最近记录: |