$ on加载一次,以供新引用使用AngularFire 0.5.0 [英] $on loaded fires once for new references AngularFire 0.5.0

查看:56
本文介绍了$ on加载一次,以供新引用使用AngularFire 0.5.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,正在使用 pushState 导航路线:

Let's say were using pushState to navigate routes:

$locationProvider.html5Mode(true);

有两条带有两个不同控制器的路由:

And there are two routes with two different controllers:

$stateProvider.state('one', {
  url:'/one',
  templateUrl:'one.html',
  controller: 'oneCtrl'
});

$stateProvider.state('two', {
  url:'/two',
  templateUrl:'two.html',
  controller: 'twoCtrl'
});

oneCtrl创建对与twoCtrl相同资源的新引用:

oneCtrl creates a new reference to the same resource as twoCtrl:

.controller('oneCtrl', ["$scope", "$firebase", function($scope, $firebase) {

  var oneRef = new Firebase("https://example.firebaseio.com/stuff");
  $scope.stuff = $firebase(oneRef);
  $scope.stuff.$on("loaded", function(value) {
    console.log(value);
  });
}])

.controller('twoCtrl', ["$scope", "$firebase", function($scope, $firebase) {

  var twoRef = new Firebase("https://example.firebaseio.com/stuff");
  $scope.stuff = $firebase(twoRef);
  $scope.stuff.$on("loaded", function(value) {
    console.log(value);
  });
}])

  • 如果我们导航到/one,则$on("loaded")事件会按预期触发-是oneRef唯一的事件.
  • 如果我们随后从/one导航到/two,则不会触发$on("loaded")事件.
    • If we navigate to /one the $on("loaded") event fires as expected - unique to the oneRef.
    • If we then navigate from /one to /two the $on("loaded") event does not fire.
    • 如果实例化了一个新的引用-twoRef-为什么回调不第二次触发?

      If a new ref was instantiated - twoRef - why doesn't the callback fire a second time?

      推荐答案

      这是由于以下事实:本地缓存的数据在Firebase中同步触发了value事件.

      This is due to the fact that locally cached data fires value events synchronously in Firebase.

      在第一次加载时,angularFire的 _getInitialValue 方法.但是,在第二次加载时,由于该值已经是本地值,因此广播事件是同步发生的,因此在附加$ on('loaded'...)处理程序之前.

      On the first load, the server is contacted asynchronously by angularFire's _getInitialValue method. However, on the second load, since the value is already local, the broadcast event happens synchronously, and therefore before your $on('loaded'...) handler gets attached.

      有两个想法:如果控制器正在使用相同的$ firebase数据,则在大多数情况下,应该只有一个.应该将其移至服务并进行相应的共享.

      A couple thoughts come to mind: If the controllers are utilizing the same $firebase data, there should probably--in most common use cases--only be one. It should be moved to a service and shared accordingly.

      另一种解决方法是将加载的状态存储在服务或$ rootScope中.

      Another workaround would be to store the loaded state in a service or in the $rootScope.

      最终,它应该在angularFire中进行了纠正,以便即使事件触发,加载的事件也会触发值"已经同步加载.

      Ultimately, it should be corrected in angularFire so that the loaded event triggers even if the 'value' is already loaded synchronously.

      这篇关于$ on加载一次,以供新引用使用AngularFire 0.5.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆