programing

호출 후 angularjs에서 $watch 바인딩 해제

sourcejob 2023. 3. 5. 09:43
반응형

호출 후 angularjs에서 $watch 바인딩 해제

다음과 같이 $워치를 풀 수 있다는 것을 알고 있습니다.

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

워치 기능 선언에서 워치를 풀 수 있습니까?그럼 시계가 한 번 실행되면 저절로 풀리는 건가요?예를 들어 다음과 같습니다.

$scope.$watch("tag", function () {
    unbindme()
});

이미 하고 있는 것과 같은 방법으로, 기능내의 「등록 해제」를 호출할 수 있습니다.

var unbind = $scope.$watch("tag", function () {
    // ...
    unbind();
});

왜냐면tag는 표현식으로, 값이 수신되면 원타임바인딩을 사용하여 바인드를 해제할 수 있습니다.

$scope.$watch("::tag", function () {});

angular
.module('app', [])
.controller('example', function($scope, $interval) {
  $scope.tag = undefined
  $scope.$watch('::tag', function(tag) {
    $scope.tagAsSeen = tag
  })
  $interval(function() {
    $scope.tag = angular.isDefined($scope.tag) ? $scope.tag + 1 : 1
  }, 1000)
})
angular.bootstrap(document, ['app'])
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body ng-controller="example">
Tag: {{tag}}
<br>
Watch once result: {{tagAsSeen}}
</body>
</html>

bindonce 디렉티브가 필요할 수도 있습니다.

https://github.com/Pasvaz/bindonce

var unbindMe=$scope.$watch('tag',function(newValue){
    if(newValue){
       unbindMe()
    }
})

비슷한 질문처럼 @Kris의 답변을 약간 개선하면 프로젝트 전체에서 보다 스타일리시하고 재사용할 수 있습니다.

.run(function($rootScope) {
    $rootScope.see = function(v, func) {
        var unbind = this.$watch(v, function() {
            unbind();
            func.apply(this, arguments);
        });
    };
})

이제 스코프 프로토타입을 상속받았기 때문에 쉽게 사용할 수 있습니다.

$scope.see('tag', function() {
    //your code
});

그리고 구속 해제에 대해 전혀 걱정하지 마세요.

언급URL : https://stackoverflow.com/questions/19394204/unbinding-watch-in-angularjs-after-called

반응형