I have an event listener that is in a function. Both the listener and the emitter are in the same function.
When the event fires, a variable is incremented. So far so good. But when I call the function several times, the listener is triggered several times in the same function call.
var test = function() {
var completeStatus = 0;
$(document).on('gt', function() {
console.log(++completeStatus);
});
$(document).trigger('gt');
}
test();
test();
test();
It expect it to output 1 three times as the function is called three times. But it outputs:
0
1
0
2
1
Why is that and how to obtain the desired behaviour?
Here's a jsfiddle to try it out.
test, its binding a listener on the eventgtand firing agtevent to all listeners binded. (not only the one you created before )completeStatusvariable, so just think that you have multiple subscribers.++completeStatus, which produces1 2 1 3 2 1, and in your fiddle you havecompleteStatus++, which produces0 1 0 2 1 0.