如何在ember.js中使用ObjectProxy在原型上代理方法?
我有一个简单的ObjectProxy,我想让调用方法变得简单(er)。例如,我计划“代理”的对象有一个名为foo和bar的方法-它们将不可用,直接导致我这样做如何在ember.js中使用ObjectProxy在原型上代理方法?,ember.js,Ember.js,我有一个简单的ObjectProxy,我想让调用方法变得简单(er)。例如,我计划“代理”的对象有一个名为foo和bar的方法-它们将不可用,直接导致我这样做 this.get("model").get("content").foo(); this.get("model").get("content").bar(); 相反,我更希望foo和bar表现得像在物体上一样 this.get("model").foo(); this.get("model").bar(); 我可以通过在ObjectP
this.get("model").get("content").foo();
this.get("model").get("content").bar();
相反,我更希望foo和bar表现得像在物体上一样
this.get("model").foo();
this.get("model").bar();
我可以通过在ObjectProxy本身上硬编码foo和bar方法来实现这一点(长期),然后像这样提取内容并手动调用方法w/apply
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)
});
如果我想这样代理每个“方法”-我如何设置原型,使其不会损害ember已经建立的树?我不一定推荐这样做,但如果您不想总是定义函数,这是一个想法。老实说,这不是一个可怕的想法添加到灰烬,我讨厌去两个层次的深度,以达到功能 代码更改 我认为跟踪添加的方法,并可能在内容更改后进行清理不会是一件可怕的事情,但我怀疑单个对象代理通常包含多个底层对象 例子 例如:
需要注意的是,在定义内容之前,不存在任何方法,但通常我们在开始处理对象之前就已经解析了对象。不能使用
this.get(“model.content”).foo()代码>?为什么不使用混音器?这很棘手,因为对象代理通常用于异步对象。这里也是这样,对吗?关于异步用法正确-我愿意做某种类型的保护子句,这是一个选项(使null或未解决的问题更少)@JamesConkling正确-您链接的recordProxy是我最终从这个Q/a构建的。核心思想是我需要一个“shell”在实际模型可用之前(在某些异步操作完成之后),可以充当代理的模型的。这个抽象(连同ember中的核心ObjectProxy本身)帮助解决了这个问题:)太棒了!谢谢你给我一个想法,让我看看:)
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);
}
}
}
})
});
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();