views:

3716

answers:

4

I'm trying to perform a specific action when I close a jQuery UI dialog. Here's a simplified version of my code:

 $('a.open-trigger').click(function(){
  var test = 'hello';

  $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});
  $('#dialog').dialog('open');

  $('a.close-trigger').click(function(){
   alert(test);
   $('#dialog').dialog('close');
  });
 });

The first time I close the dialog, I get the expected alert with the word "hello". If I open the dialog a second time, and close it, I get the "hello" alert twice. If I open and close it a third time, I get three alerts, and so on.

Why are these alerts duplicating themselves? I would want to the alert to only show up once on close, no matter how many times I open/close the dialog.

Thanks! Simon

+2  A: 

You are attaching additional event handlers every time you call .click. That is why it is duplicating.

$('a.close-trigger').click(function(){
                    alert(test);
                    $('#dialog').dialog('close');
            });

Pull that code out onto the same level as the other event binding and it should work as expected.

geowa4
+1  A: 

You've bound a function to the open button that adds a event handler to the close button each time the open event is fired. You should add your close event handler somewhere outside of 'a.open-trigger' event function...

$('a.open-trigger').click(function(){
        var test = 'hello';

        $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});
        $('#dialog').dialog('open');
});

$('a.close-trigger').click(function(){
        alert(test);
        $('#dialog').dialog('close');
});
Lunchy
A: 

You need to take the close click event handler out of the open click event handler

$(function() {
    $('#dialog').dialog({bgiframe: true, dialogClass: 'change', resizable: false, draggable: false, modal: true, height: 334, width: 450, autoOpen: false, show: 'fade'});

    $('a.open-trigger').click(function(){    
        $('#dialog').dialog('open');
    });


    $('a.close-trigger').click(function(){
        alert("hello");
        var myDialog = $('#dialog');
        if (myDialog.dialog('isOpen'))
            myDialog.dialog('close');
    });
});
Russ Cam
A: 

What if my wanted my to pass the value of what was clicked to trigger the dialog to the alert, like so:

$('a.open-trigger').click(function(){ var element = $(this).html() $('#dialog').dialog('open'); });

And then alert(element) on close?

Simon
Just discovered global variables. That did the trick.
Simon
Global variables are bad bad bad...
Will Morgan