I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit
and take action only when both have occurred.
For example, if the events are triggered in the following sequence:
$scope.$emit('first');
// do nothing
$scope.$emit('second');
// execute something
$scope.$emit('first');
// Do nothing
$scope.$emit('first');
// Do nothing
$scope.$emit('second');
// execute something
Is there any built-in way to achieve this? Ideally something like
$scope.$on('first', 'second', function() {});
I have considered the following approach:
var triggeredEvents = [];
$scope.$on('first', function() {
notifyEventTriggered('first');
});
$scope.$on('second', function() {
notifyEventTriggered('second');
});
function notifyEventTriggered(event) {
if (triggeredEvents.indexOf(event) == -1) {
triggeredEvents.push(event);
}
if (triggeredEvents.length > 1) {
execute();
triggeredEvents.length = 0;
}
}
Is there a simpler way to accomplish this? Or any suggestions on how to enhance it? Besides creating a service for this purpose.
Thank you