Question

This works just as expected but I don't like it.

$('#login-form').on('submit', function(event){
  event.preventDefault();
  init.login();
});

var init = {
  login: function() {
  // do login stuff
  }
};

This is what I want but it does not work.

$('#login-form').on('submit', init.login(event));

var init = {
  login: function(event) {
  event.preventDefault();
  // do login stuff
  }
};

Why?

Was it helpful?

Solution

It will work, you're calling the function (the value given as a callback will be the result of the function) rather than passing it as a value

$('#login-form').on('submit', init.login);

OTHER TIPS

init.login(event) calls the function init.login, passing the (non-existent) variable event to it. If you want to pass the function itself as callback, don't call it:

$('#login-form').on('submit', init.login);

You will have to declare that function before you pass it though, at this point init.login is undefined.

You're already calling the function in that line (with undefined, there is no event yet). You need to pass the function itself (not its result):

$('#login-form').on('submit', init.login);

Notice that init.login is still an anonymous function, it has no name :-) Also beware that the method is called with this being the login form element, not the init object. If you needed that, you'd use .on('submit', init.login.bind(init)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top