问题
I was going over this tutorial to implement sending/receiving broadcast messages in my angular 1.5 app.
so inside a controller I have this:
update(){
this.$rootScope.$broadcast('language_changed');
}
and in another controller I got this:
$rootScope.$on('language_changed', function (event, data){
this.updateStore(); <--- this here is undefined
});
}
updateStore() {
this.store = {
..
language_id: this.LanguageService.get(),
}
}
I'm wondering how can I get hold of this
inside the broadcast. This trick didn't work
回答1:
The answer that you provided is not a proper solution, you need to understand what are you doing, making hacks is not a solution. Please read the following article to get a basic knowledge about the difference between this and $scope this vs $scope
Important to know aswell concerning angular events:
$emit - Sends event up the angular three of scopes
$broadcast - Sends event down the angular three
Furthermore, please take a look at the following snippet: snippet
When you have two controllers, you don't need to both $broadcast the event from $rootScope and listen to it $on $rootScope, it can be simply listened to on a $scope level, $rootScope dependency injection is not needed. Check out the following:
app.controller('DemoCtrl', function($scope, $rootScope) {
$scope.broadCastEvent = function() {
$rootScope.$broadcast('language_changed');
};
});
Let's say that we want to broadcast an event when user clicks a button. The event is sent down the angular three of scopes, so your controller that is listening to this event can listen it on scope level, without the $rootScope dependency injection, something like this:
app.controller('DemoCtrl2', function($scope) {
$scope.$on('language_changed', function() {
$scope.eventFired = !$scope.eventFired;
});
})
The other case is when you want to $emit the event (send it up the angular three), then you would need to inject $rootScope to the controller that will be listening to that event, because only $rootScope can listen on a event that is being $emited from $rootScope. Check out the following:
Controller $emiting the event:
app.controller('DemoCtrl', function($scope, $rootScope) {
$scope.emitEvent = function() {
$rootScope.$emit('language_changed');
};
});
Controller catching the event:
app.controller('DemoCtrl2', function($scope, $rootScope) {
$rootScope.$on('language_changed', function() {
$scope.eventFired = !$scope.eventFired;
});
})
Try playing with the snippet a bit, look what happends if you want to $emit the event from $rootScope and try to catch it on the $scope level.
Hope this clarifies it a bit.
回答2:
solution was simple, using the javascript bind
hack:
$rootScope.$on('language_changed', function (event, data){
this.updateStore();
}.bind(this)); <-- bind makes the inner this same as outer this.. 😂
来源:https://stackoverflow.com/questions/48691233/how-to-access-this-inside-an-event-receiver-angular