Currently, my code works when I pass an anonymous function CONTAINING my custom method call into an event callback, but not when I try and call the custom method directly in the callback... IE:
var that = this;
// THIS WORKS:
gt.pubads().addEventListener('slotRenderEnded', function(event) {
that.onSlotRenderEnded(event);
});
// THIS DOES NOT. why?
gt.pubads().addEventListener('slotRenderEnded', that.onSlotRenderEnded(event));
I'm trying to understand why my method call needs to be wrapped in an anonymous function before it'll work. I would like to be able to just shorten the code and call the custom method directly instead of through the anonymous.
// THIS DOES NOT. why?
gt.pubads().addEventListener('slotRenderEnded', that.onSlotRenderEnded(event));
In this case, your second argument is actually the result of calling that.onSlotRenderEnded(event) (probably not a function), that's why it doesn't work.
And no. It does not require it to be an anounymous function. Just a function.
People generally use them because those action functions (that will respond to events) are, more often than not, required only at that specific moment and nowhere else.
But, still, you could do:
gt.pubads().addEventListener('slotRenderEnded', function(event) {
that.onSlotRenderEnded(event);
});
or
function someName(event) {
that.onSlotRenderEnded(event);
}
gt.pubads().addEventListener('slotRenderEnded', someName);
or
var someName = function (event) {
that.onSlotRenderEnded(event);
}
gt.pubads().addEventListener('slotRenderEnded', someName);
Or, even, in this case, since all you do is delegate,
gt.pubads().addEventListener('slotRenderEnded', that.onSlotRenderEnded);
They all should behave the same * .
The only possible difference in them is the value of this, that can only be determined at the moment of the actual call. In this case, if you want to be sure of the value this will take, you can use either use the anonymous (and then not using the this reference, but some other variable, such as the that you are already using in the question), or you can resort to $.proxy(), a utility function good for these situations, making it, in your case, something like:
gt.pubads().addEventListener('slotRenderEnded', $.proxy(that, 'onSlotRenderEnded'));
(* Of course, provided you do not have other variables with the sameName in the scope and so on.)
It does not need to be wrapped in an anonymous function. Rather, pass in the function definition without executing(by having the parenthesis) like
gt.pubads().addEventListener('slotRenderEnded', that.onSlotRenderEnded);
When passing in a callback, you have two options. Either you pass an anonymous function or you pass a function definition. In both cases, the event object will be automatically passed in as the first argument to the callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With