jquery 向回调函数传参数

来源:互联网 发布:depthmap软件下载 编辑:程序博客网 时间:2024/04/20 03:11


The solution is the binding of variables through closure.

I haven't used the .post function in jQuery, but a quick scan of the document suggests the call back should be a function pointer accepting the following:

function callBack(data, textStatus) {};

Therefore I think the solution is as follows:

var doSomething = function(extraStuff) {    return function(data, textStatus) {        // do something with extraStuff    };};var clicked = function() {    var extraStuff = {        myParam1: 'foo',        myParam2: 'bar'    }; // an object / whatever extra params you wish to pass.    $.post("someurl.php", someData, doSomething(extraStuff), "json");};

What is happening?

In the last line, doSomething(extraStuff) is invoked and the result of that invocation is a function pointer.

Because extraStuff is passed as an argument to doSomething it is within scope of thedoSomething function.

When extraStuff is referenced in the returned anonymous inner function of doSomething it is bound by closure to the outer function's extraStuff argument. This is true even after doSomethinghas returned.

I haven't tested the above, but I've written very similar code in the last 24 hours and it works as I've described.

You can of course pass multiple variables instead of a single 'extraStuff' object depending on your personal preference/coding standards.

原创粉丝点击