ShadowMage Posted September 20, 2010 Share Posted September 20, 2010 Hey guys, I'm working on a custom prompt box. I've run into an issue passing the selected value back to a callback function. Here's the code for the prompt: this.prompt = function(msg, props) { if (dlgContainer) { if (typeof(props) == 'object') { var btns = {}; if ((props.style == 'button') && (props.options)) { for (btn in props.options) { btns[btn] = function(){me.hide(props.callback,props.options[btn])}; } } else { btns = { Ok: function(){me.hide(props.callback,true)}, Cancel: function(){me.hide(props.callback,false)} } } setButtons(btns); } } showDialog.apply(this, []);};this.hide = function(callback) { this.dialog.style.display = "none"; document.body.style.overflow = initOverflow; if (callback !== undefined) { //Adjust the arguments so that the callback is not passed back var args = new Array(); for (x=0; x<arguments.length; x++) { if (x>0) { args.push(arguments[x]); } } callback.apply(this, args); }} The problem is here:btns[btn] = function(){me.hide(props.callback,props.options[btn])};With this code, the props.options[btn] doesn't get evaluated right away. So when I click a button it always sends back the value of the last option in the list. The options object might look like this: {one: "one", two: "two", three: "three}So if I click on the button for option one, it sends the value "three" back to the callback. I know why this happens. When the for loop is done, btn is still equal to 'three' and since the props.options[btn] seems to be evaluated only after the button is clicked and its associated function called. So props.options[btn] will always be props.options['three'] which is "three"Make sense?Ok, so I've found a way to make it work. I just used the eval() function so that the props.options[btn] will be evaluated with the rest of the string, like so:btns[btn] = eval("(function(){me.hide(props.callback,"+((isNaN(props.options[btn]))?("'"+props.options[btn]+"'"):props.options[btn])+")})");So with that I'll get a function like: function(){me.hide(props.callback, 'three')}which works exactly as I want, but is this the best way to accomplish this?I hope all that made sense.... Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.