$on 加载一次新的引用 AngularFire 0.5.0 [英] $on loaded fires once for new references 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 theoneRef
. - If we then navigate from
/one
to/two
the$on("loaded")
event does not fire.
如果一个新的 ref 被实例化 - 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<异步联系服务器/a> 方法.但是,在第二次加载时,由于该值已经是本地的,广播事件 同步发生,因此在您的 $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屋!