2014-03-19 3 views
0

속성의 변경 내용에 응답하는 각도 같은 범위 객체를 만들려고합니다. 이는 의도 한 동작입니다.콜백의 범위 지정 문제

x = new Scope('a', 'b'); 

x.data = { 
    name: 'Jim', 
    age : 19 
} 

x.$init(); 

x.$digest(); 

x.data.name = 'Bob'; 
x.$digest(); 
// name has been changed from "Jim" to "Bob" 

x.data.age = 200; 
x.$digest(); 

// age has been changed from "19" to "200" 

나이 키가 현재 정상적으로 작동합니다. 그러나 그 이름은 그렇지 않습니다. 나는 다음과 같은 기능의 범위 지정과 관련 용의자 :

Scope.prototype.$init = function() { 
    $$ = this; 
    $$.keys = Object.keys($$.data); 

    for(var i=0; i<$$.keys.length; i++) { 
    var key = $$.keys[i]; 

    $$.$watch(
     function(scope) { return scope.data[key] }, 
     function(newValue, oldValue, scope) { 
     if(newValue) { 
      console.log ('%s has been changed from "%s" to "%s"',key,oldValue, newValue) 
     } 
     } 
    ) 
    } 
} 
문제는이에 var key를 통과 할 것으로 보인다

: 여기 function(scope) { return scope.data[key] },를 사용하는 다른 두 가지 기능은 다음과 같습니다

Scope.prototype.$watch = function(watchFunction, listenerFunction) { 
    var watcher = { 
    watchFunction: watchFunction, 
    listenerFunction: listenerFunction 
    } 

    this.watchers.unshift(watcher) 
} 

Scope.prototype.$digest = function() { 
    var length = this.watchers.length; 
    var watcher, newValue, oldValue 

    while(length--) { 
    watcher = this.watchers[length]; 
    newValue = watcher.watchFunction(this); 
    oldValue = watcher.last; 

    if(newValue !== oldValue) { 
     watcher.last = newValue; 
     watcher.listenerFunction(newValue, oldValue, this); 
    } 
    } 
} 

은 누구 하나를 가지고있다 어떻게 그 기능을 해결할 아이디어? 콘솔에서 감시자를 초기화하면 완벽하게 작동하지만 자동화가 필요하므로 새 변수를 정의 할 때마다 감시자를 정의 할 필요가 없습니다.

+1

가능 중복 :

Scope.prototype.$createWatcher = function(key) { return function(scope) { return scope.data[key] } } 

나서 초기화 함수 :이 방법을 사용하는 것 750486/javascript-closure-inside-loops-simple-practical-example) – elclanrs

+0

감사합니다. – andy

답변

0

해결책을 찾았습니다. [- 간단한 실시 예 자바 폐쇄 내부 루프 (http://stackoverflow.com/questions/

$$.$watch(
    $$.$createWatcher(key), 
    function(newValue, oldValue, scope) { 
    if(newValue) { 
     console.log ('has been changed from "%s" to "%s"',oldValue, newValue) 
    } 
    } 
)