Chris
Chris

Reputation: 2646

Cannot pass jQuery object.method to another function to be executed

I have the following JavaScript:

function MyMethod(func)
{
  func();
}

$('#Btn').on('click', function(e)
{
  e.preventDefault();

  var form = $(this).parent();

  MyMethod(form.submit);
});

http://codepen.io/chrisnicholson/pen/YGxOdJ

This doesn't work, giving the following error in Chrome:

jquery.min.js:4 Uncaught TypeError: Cannot read property 'trigger' of undefined

If I modify the call to MyMethod to use the following then it works:

MyMethod(function(){
  form.submit();
});

http://codepen.io/chrisnicholson/pen/amyRXX

Can someone explain why this is?

Upvotes: 0

Views: 49

Answers (3)

Boldewyn
Boldewyn

Reputation: 82814

Ah, good ol' binding of this at work! If you only provide the method, it will not be called on the form but on the global object, like

submit.call(window) // resp. undefined in strict mode. Hence the error, I guess.

where what you want is

submit.call(form)

One way to fix this: Bind the submit method to the form:

MyMethod(form.submit.bind(form));

Upvotes: 2

jonnyhocks
jonnyhocks

Reputation: 131

Without the parentheses, .submit would just be a property of the jQuery object that you have. In this instance, your form.

Adding the parentheses actually calls the .submit() method on the form object.

Upvotes: -1

Sudharsan S
Sudharsan S

Reputation: 15403

Your code be. Just pass the object is enough.

function MyMethod(formSubmit)
{
  formSubmit.submit();
}

$('#Btn').on('click', function(e)
{
  e.preventDefault();

  var form = $(this).parent();

  MyMethod(form);
})

Upvotes: 0

Related Questions