$on loaded fires once for new references AngularFire 0.5.0

隐身守侯 提交于 2019-12-10 20:54:12

问题


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 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);
  });
}])
  • 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.

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


回答1:


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

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.

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.

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

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



来源:https://stackoverflow.com/questions/20768258/on-loaded-fires-once-for-new-references-angularfire-0-5-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!