Haris Z
Haris Z

Reputation: 119

Pass params to function using on()

    $(document).on('click', '#my', myFunc('param'));

function myFunc(param){
    //do something
}

is this snytax wrong? I got error of jquery-1.10.2.min.js:3 Uncaught TypeError: ((x.event.special[i.origType] || (intermediate value)).handle || i.handler).apply is not a function

Upvotes: 0

Views: 186

Answers (3)

Ali
Ali

Reputation: 1085

You can send data object as third parameter for on() like below:

$(document).on('click', '#my', {p: 'World'}, myFunc);

and in the function, you can access the data object using event.data when the event is triggred like below:

function myFunc(event) {
  console.log('Hello, ' + event.data.p);
}

See this page at section Passing data to the handler: http://api.jquery.com/on/#passing-data

Upvotes: 3

Regis Portalez
Regis Portalez

Reputation: 4860

This is indeed wrong. 'on' callback expects [http://api.jquery.com/on/] an event as first parameter. In it's current form, your code has no chance to work since myFunc('param') is not a function (it's the result of it's evaluation).

You can simply wrap your inner function this way:

$(document).on('click', '#my', function() { myFunc('param'); });

function myFunc(param){
    //do something
}

but if you want to properly use jquery in that handler, you need to bind this:

$(document).on('click', '#my', function() { myFunc.bind(this)('param'); });

    function myFunc(param){
        //do something
    }

You could also make your function return another function:

$(document).on('click', '#my', myFunc('param') );

    function myFunc(param){
         return function() {
         };
    }

Here is a complete fiddle

function myFunc1(p) {
  return function() {
    $(this)[0].innerHTML = "modified by " + p;
  };
}

function myFunc2(p) {
    $(this)[0].innerHTML = "modified by " + p;
}

$(document).on("click", "#one", myFunc1("inner wrapping"));
$(document).on("click", "#two", function() { myFunc2.bind(this)("outer wrapping");});
div {
  width: 300px;
  background-color: yellow;
  text-align: center;
  margin-top: 10px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one">one</div>
<div id="two">two</div>

Upvotes: 0

Martin Schneider
Martin Schneider

Reputation: 3268

You are not binding the myFunc with a certain parameter but instead are calling the function myFunc('param') and are binding the result of that method call.

One way to do what you want is wrapping your call inside another function:

$(document).on('click', '#my', function() { myFunc('param') });

Upvotes: 1

Related Questions