$ scope绑定vs $广播为app计时器

时间:2013-10-22 23:01:14

标签: angularjs angularjs-directive

我对将Timer服务的时间值绑定到多个指令的最佳方法感到困惑。下面有两种方法,我不确定什么是最佳实践,或者一种方法的性能优势是否存在。

在下面的代码中有2个定时器,第一个提供返回值,而第二个定时器广播时间。控制器通过调用第一个工厂的方法更新其股票价值,指令通过$ on call更新其价值。

他们都工作得很好,但我相信一方面有一些优势。

非常感谢任何输入。

'use strict';

var app = angular.module('ticker');

/**
 * Timer that provides the current time when called directly
 */
app.factory('Timer', function($timeout) {

  var _currentTime = 0;

  var tick = function() {
    $timeout(function() {
      _currentTime += 1;
      tick();
    }, 2000);
  };

  tick();  // start the timer

  return {
    currentTime: function() { return _currentTime; }
  };

});


/**
 * Timer that broadcasts the current time
 */
app.factory('BroadcastTimer', function($timeout, $rootScope) {

  var _currentTime = 0;

  var tick = function() {
    $timeout(function() {
      _currentTime += 1;
      $rootScope.$broadcast('tick', _currentTime);
      tick();
    }, 2000);
  };

  tick();  // start the timer
});


/**
 * Handle the list of all the user's current stocks
 */
app.controller('StocksCtrl', function ($scope, Timer) {

  /**
   * List of all the user's current watched stocks
   */
  $scope.watchedStocks = [
    { name: 'Google', symbol: 'GOOG', closings: [ 20, 23, 25, 24, 26, 30, 26, 30, 34, 40, 47, 50 ] },
    { name: 'Apple',  symbol: 'AAPL', closings: [ 12, 15, 17, 13, 18, 21, 17, 24, 28, 33, 29, 34 ] },
  ];

  /**
   * Bind the current time to the Time factory
   */
  $scope.currentTime = function() {
    return Timer.currentTime();
  };

});


/**
 * Allows one to watch a stock and buy when the price is right.
 */
app.directive('watch', function(BroadcastTimer) {
  return {
    restrict: 'E',
    templateUrl: 'watch.html',
    scope: {
      stock: '='
    },
    controller: function($scope) {
      /**
       * Listen to the BroadcastTimer's tick
       */
      $scope.$on('tick', function(event, time) {
        var timeIndex = time % $scope.stock.closings.length;
        $scope.price = $scope.stock.closings[timeIndex];
      });
    }
  }
});

1 个答案:

答案 0 :(得分:1)

以下是Angular,Misko Hevery的原创作者之一,参加活动:

  

“一般来说,对于应用程序来说,事件不太有用,特别是因为Angular有数据绑定。事件的许多内容都是数据绑定,我们已经为你做了。所以是否使用的问题事件是你想要两个组件的紧密耦合。如果你真的希望它们在一定距离,那么事件可能就是答案。但是大多数情况下注入服务或进行直接通信可能是首选的,而且更加强大处理这些事情。但这取决于你的情况“

你可以在他的演讲中看到他对此的讨论,我强烈推荐“Angular Best Practices”http://www.youtube.com/watch?v=ZhfUv0spHCY&list=TLJGdxZrHg3GcIgr_4ZzOcVQuXUhNWOOgt

跳到53:37听他讲这个。

所以,基于此,我会推动你远离$ broadcast解决方案。但我也打赌,$ broadcast解决方案需要更多的计算,特别是在复杂的页面上,因为需要遍历DOM。但我没有数据支持这一点。