loops - Javascript: Passing custom arguments to a callback function -


i have callback function setup:

var contextmenu = []; var context = [ { "name": "name1", "url": "url1" }, {"name": name2", "url: "url2" } ]; for(var i=0; < 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 url value passed callback last value in context variable - in case "url2". expecting pass specific values each "instance" of callback, callback seems remember same value, last time referred.

i kind of stuck. appreciated.

ps: using jquery contextmenu which, understanding, not support sending custom data callback functions. in context have problem. suggestions overcome in environment helpful!

use additional closure.

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

see creating closures in loops: common mistake , other questions on topic, , question added pool.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -