作用域性能 = 在angular指令中的表现

3
我编写了一个指令,大致是这个样子:

'use strict';
myApp.directive('mySwitchOnOff', [
  '$rootScope', function($rootScope) {
    return {
      restrict: 'C',
      replace: false,
      scope: { isActive: '='},
      templateUrl: 'urlToTample',
      link: function(scope, element, attrs) {
        scope.toggleVisibility = function(section, module) {
            //Do something with the scope.isActive
        };
      }
    };
  }
]);

这个指令使用了来自父级作用域的 isActive。当用户点击按钮时,toggleVisibility 函数会被执行。我认为没有必要将来自父级作用域的 isActive 进行绑定,通过传递 $event 给函数并检查目标是否有活动类,我可以找到按钮是否是 isActive。所以我把指令改写成了这样:

'use strict';
myApp.directive('mySwitchOnOff', [
  '$rootScope', function($rootScope) {
    return {
      restrict: 'C',
      replace: false,
      templateUrl: 'urlToTample',
      link: function(scope, element, attrs) {

        scope.toggleVisibility = function(e, section, module) {
         isActive = j$(e.target).hasClass('active');
         //Do something with the isActive
        };
      }
    };
  }
]);

我的问题是:从性能/最佳实践的角度来看,你认为哪种方式更好?是将父作用域绑定还是将$event传递到函数中?

1个回答

0

有趣的问题,

我认为既然您已经使用ng-click调用了摘要循环,而不是查询dom(即使hasClass是相当低性能的调用)-即绑定父作用域将更快。

hasClass的含义: (来自jquery源代码)

var className = " " + selector + " ",
            i = 0,
            l = this.length;
        for ( ; i < l; i++ ) {
            if ( this[i].nodeType === 1 &&
                (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {

                return true;
            }
        }

        return false;

监视周期也不便宜,但它仍然会发生,因此将检查引用并根据需要触发监视操作,但由于它已经发生,所以我认为这样更快。

但我只是猜测而已 :)


我会等待更多的答案,让我们拭目以待。谢谢! - Avraam Mavridis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接