对同一个变量重复 $watch 是否有成本?

Is there a cost to repeating a $watch for the same variable?

我有一些 textAngular 代码,我在其中多次观察范围内的变量?有没有一种简单的方法只创建一次这个手表,或者我可以检测到它存在吗???

代码段为:

 taRegisterTool('fontColor', {
    display: "<button colorpicker type='button' class='btn btn-default ng-scope'  title='Font Color'  colorpicker-close-on-select colorpicker-position='bottom' ng-model='fontColor' style='color: {{fontColor}}'><i class='fa fa-font '></i></button>",
    action: function (deferred) {
      var self = this;
      self.$watch('fontColor', function (newValue) {
        self.$editor().wrapSelection('foreColor', newValue);
      });
      self.$on('colorpicker-selected', function () {
        deferred.resolve();
      });
      self.$on('colorpicker-closed', function () {
        deferred.resolve();
      });
      return false;
    }
  });

每次单击此按钮时,都会执行此操作。这个 $watch 导致创建并继续存在多个实例。

根据下面 'npe' 的有用评论,我修改了代码以防止多次创建手表。

新代码:

taRegisterTool('fontColor', {
        display: "<button colorpicker type='button' class='btn btn-default ng-scope'  title='Font Color'  colorpicker-close-on-select colorpicker-position='bottom' ng-model='fontColor' style='color: {{fontColor}}'><i class='fa fa-font '></i></button>",
        action: function (deferred) {
          var self = this;
          if (typeof self.listener == 'undefined') {
            self.listener = self.$watch('fontColor', function (newValue) {
              console.log(newValue);
              self.$editor().wrapSelection('foreColor', newValue);
            });
          }
          self.$on('colorpicker-selected', function () {
            deferred.resolve();
          });
          self.$on('colorpicker-closed', function () {
            deferred.resolve();
          });
          return false;
        }
      });

感谢您的见解!

根据 https://whosebug.com/users/1344008/npe 的评论和建议添加的日志消息,很明显,在这种情况下,手表被创建了多次,据我所知,通过查看日志输出:清楚每个手表都被添加,即使观察到完全相同的变量,也需要跟踪添加时返回的侦听器,以便将其删除。这完全有道理......我只是没有想得那么清楚:-)所以我修改了代码以消除这种低效率。感谢那些看过这篇文章的人。