Possible Duplicate:
Javascript Closure Problem
In the following code, TrueThis.aChoices[i]['CallBack'] is a function when the click event is created and “false” when the click event actually occurs. How do I get the function reference into the click event handler?
My Object:
ATK.MultiChoiceDialog = function() {
var TrueThis = this;
var aChoices;
this.Show = function(sTitle,sPrompt,aChoices){
this.aChoices = aChoices;
var HTML = '[snip]';
$('body').append(HTML);
for(var i in this.aChoices)
{
console.log(TrueThis.aChoices[i]['CallBack']); // shows "function"
$('#ATKDialogButton'+i).click(function(e){
console.log(TrueThis.aChoices[i]['CallBack']); // shows "false" ???
if(TrueThis.aChoices[i]['CallBack'])
{
TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
}
});
}
}
};
I’ve also tried this:
for(var i in this.aChoices)
{
var CB = TrueThis.aChoices[i]['CallBack'];
console.log(CB); // function
$('#ATKDialogButton'+i).click(function(e){
console.log(CB); // false
if(TrueThis.aChoices[i]['CallBack'])
{
TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
}
});
}
jQuery has a built-in way of handling this by passing event data to the callback function being bound to the event.