it-source

AngularJS : 클리어 $watch

criticalcode 2022. 12. 9. 21:53
반응형

AngularJS : 클리어 $watch

내 Angular에 시계 기능이 있어JS 어플리케이션

$scope.$watch('quartzCrystal', function () {
   ...
}

단, 어떤 조건(이 예에서는 1페이지 어플리케이션에서 페이지 변경) 후에는 워치를 정지합니다(타임아웃 클리어 등).

내가 어떻게 그럴 수 있을까?

$watch등록 해제 함수를 반환합니다.콜을 하면, 그 콜이$watcher.

var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch

scope.$watch는 호출할 수 있고 워치의 등록을 취소하는 함수를 반환합니다.

예를 들어 다음과 같습니다.

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

또, 콜백내의 워치를 클리어 하는 경우는, 콜백내의 워치를 클리어 할 수도 있습니다.그러면 $watch가 사용되기 전까지 활성 상태를 유지할 수 있습니다.

이렇게...

var clearWatch = $scope.$watch('quartzCrystal', function( crystal ){
  if( isQuartz( crystal )){
    // do something special and then stop watching!
    clearWatch();
  }else{
    // maybe do something special but keep watching!
  } 
}

당신의 $watch가 전화를 걸고 있을 때dynamically그러면 인스턴스가 생성되므로 등록 해제 기능을 호출한 후$watch기능.

if(myWatchFun)
  myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});

이상적으로는 모든 커스텀 워치는 스코프를 벗어날 때 삭제해야 합니다.

메모리 관리와 앱 퍼포먼스 향상에 도움이 됩니다.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

감시자가 너무 많아 모두 클리어할 필요가 있는 경우 어레이에 밀어넣고 모든 감시자를 파괴할 수 있습니다.$watch고리를 틀어서.

var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
   //do something
}));    

for(var i = 0; i < watchers.length; ++i){
    if(typeof watchers[i] === 'function'){
        watchers[i]();
    }
}

watchers = [];

언급URL : https://stackoverflow.com/questions/14957614/angularjs-clear-watch

반응형