両方のソリューションの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
各時間プロパティの変更のいずれかと呼ばれています。しかし、オブザーバーは熱心に解雇されているので、関数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でいるかもしれないと呼ばれているということですあなたが探している行動です。
他ノート
これらの溶液の代わりに偽の観察者(等init
、willDestroy
、などの特性に)またはexplicit list of properties to observe設定避けるために、オブジェクト自体にオブザーバを定義するObjectProxy
を使用します。
このソリューションは、キーがcontent
に追加されるたびにオブザーバを追加するために、プロキシのsetUnknownProperty
をオーバーライドして動的プロパティの監視を開始するように拡張できます。 willDestroy
は同じままです。
リファレンス
[1]これはすぐに変更される可能性がありますASYNオブザーバー
のおかげでしまうこのhttp://stackoverflow.com/questions/11623645/ember-js-observer-for-すべての値/ 11679850#11679850あなたのために働く? –