0

I have a jquery script like this:

$(document).on('click', '.someClass', function(e){
    e.preventDefault();
    // Some code...
});

I would like to rewrite this as:

blah = {
    init: function() {
        e.preventDefault();
        // Some code...
    }
}

$(document).on('click', '.someClass', blah.init);

But how do I pass the e variable to the object?

3
  • 2
    Your object literal is totally messed up. Just use a normal function. Commented Jan 15, 2015 at 20:37
  • 1
    init: function(e) { ... } Commented Jan 15, 2015 at 20:37
  • When should I use an object literal and when should I use a normal function? Commented Jan 15, 2015 at 20:47

3 Answers 3

2

You need to put init as a function :

blah = {
    init: function(e) {
        e.preventDefault();
        // Some code...
    }     
}
Sign up to request clarification or add additional context in comments.

4 Comments

do I need to also do something like blah.init(e) when calling it?
No, just give the function as callback just like you did
Since you are using jQuery to setup the click event it will pass the event to your function for you. See api.jquery.com/on/#event-handler
It is just the same for plain Javascript - (without jQuery)
1

Just try with:

blah = {
    init: function(e) {
        e.preventDefault();
        // Some code...
    }
}

Comments

1

To use an object literal's function as an event handler's callback, you must set the parameters of the literal's function equal to the parameters which the event callback requires, if you wish to access them.

Like so:

var blah = {
  init: function(e) { // we want to access the event object, so we set it as a function param
    console.log(e);
    alert('bye');
  }
}

$(document).on('click', blah.init);

1 Comment

Your code was actually incorrect. You didn't pass e to the literal's function as an argument, nor do you need to call the function in an anonymous callback, you can just pass it directly without invoking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.