Federico Moretti Federico Moretti - 2 months ago 6
Javascript Question

$(this) is undefined and doesn't return selector using the same function

I'm having a problem using the function

main()
on 2 different events. The first event is this:

$buttonStart.on('click', main);


In the second event I need to do other things too so it's like this:

$buttonDelay.on('click', function () {
otherFunction();
main();
});


The
main()
function uses a jQuery function at the end:

$(this).ripple(100);


So, the problem is that in the first case it works perfectly, meanwhile in the second case it says:


Uncaught TypeError: Cannot read property 'defaultView' of undefined


I have no idea on what to do to fix this and why it behaves this differently.

Thank you for your help.

Answer

You can use Function.prototype.call() to set this to $buttonDelay at otherFunction, main, you can also pass the event object to the functions as second parameter to .call()

$buttonDelay.on("click", function (event) {
    otherFunction.call(this, event);
    main.call(this, event);
});
Comments