2012-12-29 5 views
9

개체 속성의 모든 변경 사항을 관찰하고 싶습니다.
다음 예제에서는 firstname 또는 lastname이 변경되면 personChanged observer가 알림을 보내려고합니다.
그러나 모든 객체 속성에 Emerson.keys()를 사용하여 일반 무언가를 적용하고 싶습니다. '성', '성'을 좀 더 일반적인 것으로 대체하는 방법은 무엇입니까? 내 예에서Ember.js : 모든 개체 속성 관찰

: firstname 또는 lastname가 변경 될 때

personChanged가 호출됩니다 :

App.MyObject: Ember.Object.create({ 
    firstname: 'first', 
    lastname: 'last', 
    personChanged: Ember.observer(function() { 
      console.log("person changed"); 
    }, 'firstname', 'lastname') 
}) 
+0

이 것 http://stackoverflow.com/questions/11623645/ember-js-observer-for- 모든 값/11679850 # 11679850 당신을 위해 일하니? –

답변

2

이 바로 인라인 관측을 사용하고있다,하지만 당신이 그냥 구문 오류가 있습니다. 그러나 핵심 단어 observes을 사용하는 것이 더 간단합니다. 그래서 저는 여러분의 모범을 약간 수정했습니다.

App.MyObject: Ember.Object.create({ 
    firstname: 'first', 
    lastname: 'last', 
    personChanged: function() { 
     //firstname or lastname changed 
    }.observes('firstname','lastname') 
}); 

참고 : 나는 속성

따옴표를 넣어

출처 :http://emberjs.com/guides/object-model/observers/

+1

Tx하지만 내 질문에 모든 개체 특성 (관찰 메서드 특성 목록을 작성하지 않고) 일반적인 솔루션을 얻는 것이었다 – fvisticot

+0

미안하지만 배열이나 하나의 개체에 모든 속성을 저장하지 않으면 그렇게 할 수있는 방법이 없습니다 그것을 관찰 한 다음 몇 가지 수동 계산을 수행하여 값을 검색하십시오. – Akash

8

이 사용자의 요구 사항에 따라 한 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/

자바 스크립트

이미가 content 객체에 존재 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] 열심히 해고되기 때문에, personChangedidempotent이어야하며,이 함수는 예제와 다릅니다. 다음 해결책은 관찰자를 게으름으로써 이것을 수정합니다.

해결 방법 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 관찰자 곧 감사를 변경 얻을 수 있습니다