I have AngularJS app with Angular Kendo as UI.
From one of the service I am sending broadcast to the controllers.
I am sending broadcast from service as below:
angular.module('MyAppModule')
.service('MyService', ['$rootScope',function($rootScope)
{
this.MESSAGE = "broadcast_msg";
function sendBroadcast(message, data)
{
console.log("I get this log");
$rootScope.$broadcast(message, data);
console.log("I don't get this log");
}
function onSomeEvent(data)
{
sendBroadcast(MESSAGE, data)
}
}]);
And in my controller:
angular.module('MyAppModule')
.controller('MyViewCtrl', ['$scope', 'MyService', function($scope, MyService)
{
function init()
{
$scope.$on(MyService.MESSAGE, function(event, data)
{
if( data.state == "some_state")
{
process()
}
});
}
function process()
{
// Destroy and remove current screen
$("#MyView").data("kendoMobileView").destroy(); // KendoMobileView is provide by Kendo
$("#MyView").remove(); // MyView - is that ID of kendo mobile view
}
}]);
If I comment destroy
and remove
calls then everything works fine.
But when I add then $rootScope.$broadcats
does not return in the service.
I need to remove
and destroy
calls as to clear the screen and related states.
How to fix this issue?
UPDATE
I am deregistering broadcast listener as below from my controller.
// While registering listener
var deregisterMessage = $scope.$on(MyService.MESSAGE, function(event, data)
{
});
// At the time of removing screen
if( deregisterMessage != null )
{
deregisterMessage();
deregisterMessage = null;
}
Don't use $rootScope.$on
from your controller, because even after your controller destroyed, event listener still exist and it cause memory leak.
it is better to create a service for each event you need to listen to or broadcast.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.