Kim
Kim

Reputation: 2777

How to call regular JS function with params within jQuery?

Is there another way to run a regular JS function with parameters passed than what I use below?
It seems redundant use a on-the-way function to do this.

function regularJSfunc(param1,param2) {
  // do stuff
}
$(document).ready(function(){
  $('#myId').change(function(){
      regularJSfunc('data1','data2');
    });
}

Using a .bind event seems much better, however I am not sure how to access the parameters.
Note: Example below doesn't work.

$(document).ready(function(){
  $('#myId').bind('change',{'data1','data2'},regularJSfunc);
}

Upvotes: 1

Views: 564

Answers (4)

Miguel Ventura
Miguel Ventura

Reputation: 10458

No.

jQuery event handlers receive a function object which they'll invoke with a single argument, the eventObject. If you want to pass your own arguments, then the alternative you have is passing an intermediate function that will invoke your final function with the arguments you want.

You can achieve that effect by passing an anonymous function, just like you provided yourself in your working example. That's also the standard way (with standard meaning what I see everyone doing) of calling a regular function with custom arguments from a jQuery event binding.

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67802

In your second example, data needs to be a map.

function myFunc( event )
{
alert( event.data.data1 );
//or alert( event.data['data1'] );
}

$(document).ready(function(){
  $('#myId').bind('change',{'data1':'some data'},myFunc);
}

Upvotes: 1

Other than using bind() and event properties, you could use partial function application:

Function.prototype.curry = function() {
 var fn = this, args = Array.prototype.slice.call(arguments);
 return function() {
  return fn.apply(this, args.concat(
   Array.prototype.slice.call(arguments)));
 };
};

(Prototype.js has this extension built in.)

Then your code could look something like

$(document).ready($('#myId').change(regularJSfunc.curry('data1','data2'));

Upvotes: 2

David Murdoch
David Murdoch

Reputation: 89312

Here is what you were trying to do:

$(function(){
    $('#myId').bind('change',{'data':["data1","some data"]},regularJSfunc);
});

then you can access the data like this:

function regularJSfunc(e){
    var data = e.data.data;
    var data1 = data[0];
    var someData = data[1];
    // do stuff with the data...
}

and an alternative approach:

$(function(){
    $('#myId').bind('change',{"data1":"data1","someData":"some data"}, regularJSfunc);
});

then you can access the data like this:

function regularJSfunc(e){
    var data1 = e.data.data1;
    var someData = e.data.someData;
    // do stuff with the data...
}

Upvotes: -1

Related Questions