【问题标题】:Unbinding $watch in angularjs after called调用后在 angularjs 中解绑 $watch
【发布时间】:2013-10-24 00:34:08
【问题描述】:

我知道你可以像这样解除 $watch 的绑定:

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

但是你可以在 watch 函数声明中取消绑定手表吗?那么在手表执行一次之后,它会自行解除绑定吗?比如:

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

【问题讨论】:

标签: javascript angularjs frameworks


【解决方案1】:

你可以像你已经做的那样做,在你的函数中调用“取消注册”:

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

【讨论】:

  • listener 最好命名为unbind
  • @daniellmb 如果我再次致电listener() 有什么问题吗?我有一段代码只有在满足条件时才会执行listener()。那么,如果我再次在外部(可能在 scope.$on('destroy') 内部)调用解除绑定函数,是否有任何问题?
  • @Dane 你可以随意调用它多次,也很容易测试
【解决方案2】:

因为tag是一个表达式,所以一旦收到值就可以使用one-time binding解绑:

$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>

【讨论】:

    【解决方案3】:

    bindence 指令可能是你需要的。

    https://github.com/Pasvaz/bindonce

    【讨论】:

      【解决方案4】:
      var unbindMe=$scope.$watch('tag',function(newValue){
          if(newValue){
             unbindMe()
          }
      })
      

      【讨论】:

        【解决方案5】:

        就像similar question 一样,对@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
        });
        

        而且完全不用担心解除绑定。

        【讨论】:

          猜你喜欢
          • 2014-04-26
          • 2014-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-16
          • 2016-06-04
          相关资源
          最近更新 更多