Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Passing custom arguments to a callback function

I have this callback function setup:

var contextMenu = [];
var context = [ { "name": "name1", "url": "url1" }, {"name": name2", "url: "url2" } ];
for(var i=0; i < context.length; i++) {
    var c = context[i];
    var arr = {};
    arr[c.name] = function() { callback(c.url); }
    contextMenu.push( arr );
}
function callback(url) {
   alert(url);
}

The problem is that the url value passed to the callback is always the last value in the context variable - in this case "url2". I am expecting to pass specific values to each "instance" of the callback, but as the callback seems to be remember the same value, the last time it was referred.

I am kind of stuck. Any help would be appreciated.

PS: I am using jQuery ContextMenu which, to my understanding, does not support sending custom data to its callback functions. It is in this context that I have this problem. Any suggestions to overcome in this environment is also helpful!

like image 337
rsmoorthy Avatar asked Feb 28 '11 16:02

rsmoorthy


People also ask

Can you pass arguments to callback function?

By default you cannot pass arguments to a callback function. For example: function callback() { console.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn);

How do you find the argument of a callback function?

To get the list of arguments without breaking functionality, overwrite the callback function in this way: var original = callback; callback = function() { // Do something with arguments: console. log(arguments); return original. apply(this, arguments); };


2 Answers

Use an additional closure.

arr[c.name] = (function(url) { 
    return function() { callback(url); }
})(c.url);

See Creating closures in loops: A common mistake and most other questions on this topic, and now your question is also added to this pool.

like image 110
Anurag Avatar answered Nov 14 '22 20:11

Anurag


You are creating a series of closure functions inside the for loop

arr[c.name] = function() { callback(c.url); }

and they all share the same scope, and hence the same c object which will point to the last element in your array after the loop finishes.

To overcome this issue, try doing this:

arr[c.name] = function(url) {
    return function() { callback(url); };
}(c.url);

Read more about closures here: http://jibbering.com/faq/notes/closures/

like image 20
ArtBIT Avatar answered Nov 14 '22 20:11

ArtBIT