I have a function which is a JQuery event handler. Because it is a JQuery event handler, it uses the this variable to refer to the object on which it is invoked (as is normal for that library).
Unfortunately, I need to manually call that method at this point. How do I make this inside the called function behave as if it were called from JQuery?
Example code:
function performAjaxRequest() {
//Function which builds AJAX request in terms of "this"
}
function buildForm(dialogOfForm) {
var inputItem;
dialogOfForm.html('...');
dialogOfForm.dialog('option', 'buttons', {
"Ok" : performAjaxRequest
});
inputItem = dialogOfForm.children(':not(label)');
//Redirect enter to submit the form
inputItem.keypress(function (e) {
if (e.which === 13) {
performAjaxRequest(); //Note that 'this' isn't the dialog box
//as performAjaxRequest expects here, it's
//the input element where the user pressed
//enter!
}
}
}
If
dialogis the object that you need to be set tothisthen:should do the trick.
Otherwise, in jQuery you can simply call the
triggermethod on the element that you want to have set tothisSay, for example, that you wanted to have a
clickevent happen on a button and you need it to happen now. Simply call:Your
#my_button‘sclickhandler will be invoked, andthiswill be set to the#my_buttonelement.If you need to call a method with a different
this… say for example, withthisreferring to the jQuery object itself, then you will want to usecallorapplyon your function.Chuck and meder have already given you examples of each … but to have everything all in one place:
SEE: A List Apart’s Get Out of Binding Situations