开发者

How to call regular JS function with params within jQuery?

开发者 https://www.devze.com 2022-12-26 17:17 出处:网络
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.

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 acces开发者_Python百科s the parameters.

Note: Example below doesn't work.

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


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'));


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);
}


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.


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...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号