I’m trying to write my own modal popup window using a jQuery function. However, I’m having a problem whereby the latest window I create will be the window that is shown by all controls. I’m obviously doing something totally wrong.
Please see the following jsFiddle: http://jsfiddle.net/Ff34s/5/
I would of expected the results of the following code…
$(document).ready(function () {
// Put the editor in a dialog window
$("#test1").gttdialog({
});
// Put the editor in a dialog window
$("#test2").gttdialog({
});
$("#test1").gttdialog.show();
});
…to show the div containing 1, but instead I get the div containing 2.
Why is this? I can only guess that the chunk of code where this goes wrong is during the each iteration:
// Create the dialog window
this.each(function () {
var $this = $(this);
var controls = renderDialog($this);
hide(controls);
// Handle the resize event
$(window).resize(function () {
keepCentered(controls.dialog);
maintainMask(controls.mask);
});
$this.gttdialog.show = function () {
show(controls);
};
$this.gttdialog.hide = function () {
hide(controls);
};
});
Only the latest creation of the variable controls seems to be kept in scope.
UPDATE:
The problem is due to:
$this.gttdialog.show = function () {
show(controls);
};
$this.gttdialog.hide = function () {
hide(controls);
};
They get reassigned on the 2nd iteration. How can I make this work for all iterations? I’m obviously doing something totally wrong with jQuery functions.
The problem is
gttdialogis a property that is shared by all jQuery objects (it refers to$.fn.gttdialog). Whenever you call$("#test2").gttdialogyou are overwriting this property.So what you’d have to do is to attach the controls to this particular instance. You could do:
But then you have to keep a reference to the object, because calling
jQuerywill create a new jQuery object:Another option would be to work with
.data().Update: Considering your code below, I think you can have it much easier. I would store the controls with
.data():and
Then you don’t have to deal with IDs.