ionic publish and subscribe example

By: Ryan Wong at

Here’s the scenario. I want to run an expensive function on a time interval that is called on many pages.
If someone else also calls the expensive function, it will ignore this request.

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
angular.module('app', [])
.run(['$ionicPlatform', '$rootScope',
function($ionicPlatform, $rootScope) {

$rootScope.startJob = true;
$rootScope.$on('longjob', function (event, data) {
if ($rootScope.startJob){
$rootScope.startJob = false;
setTimeout(function(){
longFunction(data, function(e, result){
//reset $rootScope
$rootScope.startJob = true;
});
}, 2000);
}
});


}]);

controller.js

1
2
3
function ctrl($scope){
$scope.$emit('longjob', {});
}