PDA

View Full Version : Lazy initialize pushes variable out of scope



leveille
4 Aug 2007, 5:30 PM
In the app I am working on, when I lazy initialize my dialog it cause one of my variables to behave very strangely. The variable is blockId. This section of code is part of a function that is called as part of a click event for a group of elements on my page. The id of the element which has been clicked is stored in blockId. The first element I click sends its id to this function, and the function executes properly. With ever successive click, the correct id is sent down to blockId, however somehow the very same variable blockId within the lazy initialized block is retaining it's value from the previous element click.

I'm sure this has to do with my lack of understanding of lazy initializing, however how can I "reset" the value of a referenced variable in this block with each click event?



function showDialog(id, data){
var blockId = id;
var animate = Ext.get(blockId);

alert(blockId);

if(!dialog)
{
dialog = new Ext.LayoutDialog("bai-dialog", {
modal:true,
resizable:false,
width:594,
height:383,
shadow:true,
proxyDrag: true,
closable: false,
center: {
autoScroll:true
}
});

dialog.addKeyListener(27, function(){
cancel(dialog, blockId);
}, dialog);

dialog.setDefaultButton(dialog.addButton('Cancel', function(){
cancel(dialog, blockId);
}, dialog));

dialog.addButton('Submit', function(){
var editorData = HtmlEditor.getValue();
alert(blockId);
save(editorData, dialog, blockId);
}, dialog);

var layout = dialog.getLayout();
layout.beginUpdate();
layout.add('center', new Ext.ContentPanel('bai-center'));
layout.endUpdate();
}

alert(blockId);

HtmlEditor = new Ext.form.HtmlEditor({
//enableColors: false,
enableFont: false,
enableFontSize: false,
name: 'bai-body',
value: data
});

HtmlEditor.setSize(570, 310);

jQuery("#bai-center").empty();
HtmlEditor.render('bai-center');
dialog.show(animate.dom);
}

evant
4 Aug 2007, 5:41 PM
It appears to be a scoping issue. You'd be best off to remove your event handler bindings outside of your lazy initialization block, like:



var blockID = 1;
if (!dialog)
{
//create dialog
}
dialog.buttons[1].purgeListeners(); //get the submit button, remove any listeners
dialog.buttons[1].setHandler(function() { ... });

leveille
5 Aug 2007, 5:15 PM
Thanks for taking the time to respond. In essence I just needed a lesson in lazy initialization and the singleton pattern. All I did was create a private variable in my code namespace and set it equal to the value of the variable I needed access to from within the lazy initialized block:



getBlockId = function() {
return blockId;
}

if(!dialog) {
...

dialog.addButton('Submit', function(){
save(HtmlEditor.getValue(), dialog, getBlockId());
}, dialog);

...
}