두 솔루션의 HTML은 동일합니다.
15, 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
을 초기화하는 동안, 모든 특성이 관찰되며,이 함수는 personChanged
마다 특성의 변화 중 하나를 호출한다. 그러나 관측자는 간절히 [1] 열심히 해고되기 때문에, personChanged
은 idempotent이어야하며,이 함수는 예제와 다릅니다. 다음 해결책은 관찰자를 게으름으로써 이것을 수정합니다.
해결 방법 2
JsFiddle : http://jsfiddle.net/2zxSq/1/
자바 스크립트
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에있는 수라고이다 당신이 찾고있는 행동.
다른 주
이들 용액 대신 또는 explicit list of properties to observe (등과 init
, willDestroy
같은 속성) 스퓨리어스 관찰자 설정 피 대상물 자체 관찰자를 정의 ObjectProxy
를 사용한다.
content
에 키를 추가 할 때마다 프록시에서 setUnknownProperty
을 무시하고 동적 특성을 관찰하기 위해이 솔루션을 확장 할 수 있습니다. willDestroy
은 그대로 유지됩니다.
참조
이 [1]이 Asyn 관찰자 곧 감사를 변경 얻을 수 있습니다
이 것 http://stackoverflow.com/questions/11623645/ember-js-observer-for- 모든 값/11679850 # 11679850 당신을 위해 일하니? –