这是可能使用两个ObjectProxy
口味,根据您的要求。两种方法的区别仅在于观察者打电话的时间和次数,他们都依赖于Ember.keys
。
这两种解决方案的HTML都是相同的。
HTML
<script type="text/x-handlebars" data-template-name="app">
Name: {{App.MyObject.firstname}} {{App.MyObject.lastname}}
<ul>
{{#each App.List}}
<li>{{this}}</li>
{{/each}}
</ul>
</script>
解决方案1
的jsfiddle:http://jsfiddle.net/2zxSq/
的Javascript
App = Em.Application.create();
App.List = [];
App.MyObject = Em.ObjectProxy.create({
// Your Original object, must be defined before 'init' is called, however.
content: Em.Object.create({
firstname: 'first',
lastname: 'last'
}),
// These following two functions can be abstracted out to a Mixin
init: function() {
var self = this;
Em.keys(this.get('content')).forEach(function (k) {
Em.addObserver(self.get('content'), k, self, 'personChanged')
});
},
// Manually removing the observers is necessary.
willDestroy: function() {
var self = this;
Em.keys(this.get('content')).forEach(function (k) {
Em.removeObserver(self.get('content'), k, self, 'personChanged');
});
},
// The counter is for illustrative purpose only
counter: 0,
// This is the function which is called.
personChanged: function() {
// This function MUST be idempotent.
this.incrementProperty('counter');
App.List.pushObject(this.get('counter'));
console.log('person changed');
}
});
App.ApplicationView = Em.View.extend({
templateName: 'app'
});
// Test driving the implementation.
App.MyObject.set('firstname', 'second');
App.MyObject.set('lastname', 'last-but-one');
App.MyObject.setProperties({
'firstname': 'third',
'lastname' : 'last-but-two'
});
虽然初始化MyObject
,其已经的content
对象上存在的所有属性被观察到的,并且每次函数personChanged
被称为任何的属性更改。但是,由于观察者急切地被触发[1],所以功能personChanged
应该是idempotent,其中示例中的功能不是。下一个解决方案通过让观察者懒惰来解决这个问题。
解决方案2
的jsfiddle:http://jsfiddle.net/2zxSq/1/
的Javascript
App.MyObject = Em.ObjectProxy.create({
content: Em.Object.create({
firstname: 'first',
lastname: 'last'
}),
init: function() {
var self = this;
Em.keys(this.get('content')).forEach(function (k) {
Em.addObserver(self, k, self, 'personChanged')
});
},
willDestroy: function() {
var self = this;
Em.keys(this.get('content')).forEach(function (k) {
Em.removeObserver(self, k, self, 'personChanged');
});
},
// Changes from here
counter: 0,
_personChanged: function() {
this.incrementProperty('counter');
App.List.pushObject(this.get('counter'));
console.log('person changed');
},
// The Actual function is called via Em.run.once
personChanged: function() {
Em.run.once(this, '_personChanged');
}
});
这里唯一的变化是,只有在the end of the Ember Run loop实际观测功能现在被称为,这可能是你正在寻找的行为。
其他说明
这些解决方案使用ObjectProxy
代替定义对象本身上的观测,以避免设置杂散观察员(性能如init
,willDestroy
,等)或explicit list of properties to observe。
通过覆盖代理上的setUnknownProperty
开始观察动态属性,每次将密钥添加到content
时添加观察者,可以扩展此解决方案。 willDestroy
将保持不变。
参考
[1]这可能很快就改变得益于ASYN观察员
将这项http://stackoverflow.com/questions/11623645/ember-js-observer-for-全部值/ 11679850#11679850为你工作? –