programing

변수 감시 및 변경

cafebook 2023. 3. 9. 22:19
반응형

변수 감시 및 변경

각진 상태JS I에는 스코프 변수를 감시하는 지침이 있습니다.변수에 특정 데이터가 포함되어 있으면 변수를 약간 변경해야 합니다.문제는 내가 변수를 변경하면$watch다시 트리거됩니다.그래서 저는 연속적인 루프가 됩니다.

scope.$watch('someVar', function(newValue, oldValue) {
    console.log(newValue);
    scope.someVar = [Do something with someVar];
});

이게 계속 트리거가 돼요.$watch말이 되네하지만 감시 변수를 바꿀 방법이 필요해요방법이 있을까요?

변수를 사용하여 변경을 감시하는 경우$scope.$watch, angular는 참조가 변경되었는지 확인합니다.만약 있다면,$watch핸들러가 실행되어 뷰가 갱신됩니다.

$watch 핸들러 내에서 스코프 변수를 변경할 경우 스코프 변수 참조가 호출될 때마다 변경되기 때문에 무한 $digest 루프가 트리거됩니다.

무한 다이제스트 문제를 회피하기 위한 요령은 참조를 내부에 보존하는 입니다.$watchangular.copy를 사용하는 핸들러(표준):

scope.$watch('someVar', function(newValue, oldValue) {
    console.log(newValue);
    var someVar = [Do something with someVar];

    // angular copy will preserve the reference of $scope.someVar
    // so it will not trigger another digest 
    angular.copy(someVar, $scope.someVar);

});

주의: 이 트릭은 객체 참조에만 적용됩니다.원시 요소에서는 작동하지 않습니다.

일반적으로 업데이트는 권장되지 않습니다.$watched그 자체 내의 변수$watch청취자하지만 때로는 피할 수 없는 경우도 있습니다.

루프 상태가 지속될 경우 내부 기능 사용

scope.$watch('someVar', function(newValue, oldValue) {
   if(newValue!==oldValue) {
    console.log(newValue);
    scope.someVar = [Do something with someVar];
   } 
});

이것이 더러운 체크의 원리입니다.매번 뭔가...$scopeAngular 변경은 스코프에 연결된 모든 항목을 통해 회전하며 더 이상 변경이 없을 때까지 계속됩니다.

그런 일을 하고 싶다면, 그 일을 확실히 해야 할 것이다.$watch함수가 유휴 상태입니다.둘 다 살펴봐야 합니다.newValue그리고.oldValue이 경우 변수에 변경 사항을 이미 적용했다는 것을 알게 됩니다.$digest루프. 어떻게 그렇게 할 수 있는지는 어떤 변화를 주느냐에 따라 달라집니다.someVar.

일반적으로 시계 기능에서 감시 변수를 변경하는 것은 바람직하지 않습니다.

Bool 변수를 사용하여 관리할 수 있습니다.

$scope.someVarChanged = false;

scope.$watch('someVar', function(newValue, oldValue) {
    console.log(newValue);
    $scope.someVarChanged = !$scope.someVarChanged!;
    if($scope.someVarChanged) {            
        scope.someVar = [Do something with someVar];
    }
});

네, 이렇게 취소할 수 있습니다.

var wathcer = scope.$watch('someVar', function(newValue, oldValue) {
    console.log(newValue);
    scope.someVar = [Do something with someVar];

});
wathcer(); // clear the watch

언급URL : https://stackoverflow.com/questions/25322780/watch-variable-and-change-it

반응형