javascript **取消绑定$ watch **

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript **取消绑定$ watch **相关的知识,希望对你有一定的参考价值。

//
// UNBIND .$WATCH
// https://www.bennadel.com/blog/2480-unbinding-watch-listeners-in-angularjs.htm
//

// In some cases you may only want to $watch() for a single change
// or only watch for changes up to a certain point.
// You can unbind a $watch() listener using the provided "deregistration" function.

// When you invoke the $watch() method, to create a binding, AngularJS returns a "deregistration" function
// This function can then be invoked to unbind your $watch() listener

// Example: watch the number of clicks that a link receives.
// And, if that number gets above 5, show a message and remove the listener


<a ng-click="incrementCount()">Click it, click it real good!</a>
{{ clickCount }}
<p ng-show="isShowingFeedback">Heck yeah, now that's how you click a link!!</p>
//

var app = angular.module( "Demo", [] );

app.controller(
    "AppController",
    function( $scope ) {
        // I keep track of how many times the user has clicked
        // the link.
        $scope.clickCount = 0;
        // I determine if the "encouraging" feedback is shown.
        $scope.isShowingFeedback = false;
        // ---
        // WATCHERS.
        // ---
        // When you call the $watch() method, AngularJS
        // returns an unbind function that will kill the
        // $watch() listener when its called.
        var unbindWatcher = $scope.$watch(
            "clickCount",
            function( newClickCount ) {
                console.log( "Watching click count." );
                if ( newClickCount >= 5 ) {
                    $scope.isShowingFeedback = true;
                    // Once the feedback has been displayed,
                    // there's no more need to watch the change
                    // in the model value.
                    unbindWatcher();
                }
            }
        );
        // ---
        // PUBLIC METHODS.
        // ---
        // I increment the click count.
        $scope.incrementCount = function() {
            $scope.clickCount++;
            // NOTE: You could just as easily have called a
            // counter-related method right here to test when
            // to show feedback. I am just demonstrating an
            // alternate approach.
        };
    }
);


//we're storing the function reference returned by the $watch() statement; 
//then, once the $watch() fires a few times, we invoke that stored method, unbinding the $watch() listener.

以上是关于javascript **取消绑定$ watch **的主要内容,如果未能解决你的问题,请参考以下文章

javascript 绑定和取消绑定悬停,根据窗口大小单击事件

如何使用 javascript 取消注册/取消绑定 Material ui 中的事件

javascript 在复制函数时取消绑定事件

JavaScript-事件

当 iPhone 从配对的 Apple Watch 收到消息时本地通知不会取消(有时)

Apple Watch 中模态序列中的“取消”标签显示错误文本 - “abbrechen”