ajoslin/angular-promise-tracker

Getting events fired multiple times. What am i doing wrong?

pareeohnos opened this issue · 1 comments

I'm trying to setup the promise tracker in a hierarchical kind of way and running into an issue.

My app has a structure where each controller inherits everything from a parent application_controller. In this application controller, I've added the following method :

$scope.track = function(trackerName, request) {

    var tracker = $scope[trackerName];
    if (!tracker) {
      tracker = promiseTracker(trackerName);
      $scope[trackerName] = tracker;
    }

    tracker.addPromise($q.when(request.$then));

    tracker.on('start', function() { $scope.$broadcast(trackerName + ':start') });
    tracker.on('success', function() { $scope.$broadcast(trackerName + ':success') });
    tracker.on('error', function() { $scope.$broadcast(trackerName + ':error') });
    tracker.on('done', function() { $scope.$broadcast(trackerName + ':done') });
  }

Then, in the child controller, I have:

$scope.meetings = Meeting.query();
$scope.track("meetingsList", $scope.meetings);
$scope.$on("meetingsList:done", function() { console.log("Whoop! - " + new Date()); });

I then have my broadcast listener listening to "meetingsList:done" which simply outputs to the console a simple message.

When I load the page and have it trigger the request, it works as expected, and I see my message appear. If I then navigate to another page and go back, it again works but I get my message twice. Repeating, it appears 3 times, and so on, increasing by 1 each time.

I'm sure that I'm doing something wrong but I'm not entirely sure what that is :(

Think I may have figured it out. I moved my tracker.on calls into the if(!tracker) block and it's working. I assume it's just keeping multiple callbacks and I simply added the same callback numerous times :(

Rookie mistake. Sorry to waste your time