I tried creating a global function and assigned it to the window object and tried to call it in a submit callback but I don’t know why $(this) still keeps referring to the window object, how can I make $(this) refer to the $(‘form’) that is calling the function?
window.someFunc = function(param) {
var someVar = $(this).serializeArray();
console.log(someVar) // returns the window object
}
$('form').on('submit', someFunc(param));
$('form').on('submit', function() {
var someVar = $(this).serializeArray();
});
No point in giving the function a parameter when it doesnt use one.
It should be noted that .on will pass an Event object to the parameter if one is given.
hi, my function relies on one argument to make it reusable throughout every page of the web app i am building, but i’m having a problem making $(this) work with my function attached to the window variable
Here you are calling someFunc() immediately, and passing its return value (which is undefined) to the event listener. This is not what you want, you’ll probably get an error sooner or later too. So just pass the actual function to the listener instead, and this will refer to the form by the time it gets called:
Mind that this passes the event object as parameter. if the function must use a parameter, there are essentially two ways to accomplish that: either store the data on the called element (e.g. via data attributes) or use a Closure.
// Closure example, the important part is that the function call returns a function
function someFunc(param)
{
return function (evt) {
doSomethingWith(param)
}
}
$('form').on('submit', someFunc(someValue));
// data example
function someFunc(evt)
{
doSomethingWith(this.dataset.someValue)
}
$('form').on('submit', someFunc);
True! Of course, with data-* attributes you’re restricted to strings; I just checked the API though and it turns out you can actually pass some data directly to the listener that will be available on the event object:
var someFunc = function (event) {
event.preventDefault()
console.log(event.data.param)
}
$('form').on('submit', { param: 'someValue' }, someFunc)
BTW @mountainman make sure to prevent the event default too – otherwise a submit callback will be pretty useless as you’ll get redirected to the form action URL anyway.