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

时间:2015-05-04 19:32:45

标签: angularjs angularjs-watch

I have some textAngular code where I watch a variable in the scope, multiple times? Is there a simple way to only create this watch once, or can I detect that it exists???

The section of code is:

 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;
    }
  });

Each time this button is clicked, this action is executed. This $watch causes multiple instances to be created and to live on.

Based on the helpful comment by 'npe' below, I have amended the code to keep the watch from being created multiple times.

New Code:

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;
        }
      });

Thanks for your insight!

1 个答案:

答案 0 :(得分:0)

根据评论并建议添加来自https://stackoverflow.com/users/1344008/npe的日志消息,很明显,在这种情况下,我会理解多次创建监视,并通过查看日志输出:很明显每个手表都被添加,即使看到完全相同的变量,也需要跟踪在添加它时为了删除它而返回的侦听器。这完全有道理......我只是没有这么清楚地思考:-)所以我修改了代码以消除这种低效率。感谢那些看过这个的人。