ps0604 ps0604 - 4 months ago 9
AngularJS Question

How can I invoke a function after two or more $scope events have been received?

For example, let's assume I need to run a function after receiving two events "eventA" and "eventB". What I usually do is to declare for each event a boolean variable, set the variable to true when the event is received, and ask if the other variable is true to run the function:

var a = false,
b = false;

$scope.$on("eventA", function(){
a = true;
if (b)
performTask();
});

$scope.$on("eventB", function(){
b = true;
if (a)
performTask();
});

var performTask = function() {
/* do something... */
};


This gets more complex if there are three or more events. Is there a design pattern to handle these cases?

Answer

You can use $q promises.

var dfdATask= $q.defer();
var dfdBTask= $q.defer();

$scope.$on("eventA", function(){
    // whatever this function does
    dfdATask.resolve(true);//or pass a value
});

$scope.$on("eventB", function(){
    //whatever this function does
    dfdBTask.resolve(true);//or pass a value
});

$q.all([dfdATask.promise, dfdBTask.promise]).then(function(){
    //be sure to pass in an array of promises
    //perform task
})