I need to observe events from a couple of jQuery UI dialogs. They all come standard with a few events that you can listen for. No problem so far.
I could use this to bind a function to the open event:
$(document).bind('dialogopen', function() {});
However I need to distinguish from which dialog the event origins. For example:
$('#dialog1').dialog();
$('#dialog2').dialog();
Opening either of them will trigger the same event. The function bound to document will fire for both dialogs when they are opened. This is not what I wish for. I found two possible solutions and neither feels great but would at least do the job.
Solution 1: Trigger a custom event by the callback function for the open event
// Trigger events
$('#dialog1').dialog({open: function() {
$(this).trigger('dialog1open')
}
});
$('#dialog2').dialog({open: function() {
$(this).trigger('dialog2open')
}
});
// Observe events
$(document).bind('dialog1open', function() {
//actions specifik to dialog 1 open event
});
$(document).bind('dialog2open', function() {
//actions specifik to dialog 2 open event
});
This way would require me to write custom functions for all events, on all dialogs when initiating them, just to forward it with an event name specific to each dialog.
Solution 2: Capture the target in the event parameter. It would look something like this:
$(document).bind('dialogopen', function(event) {
el = event.target; // get the element triggering the event
switch(el.id) { // Action depending on the triggers id
case dialog1:
//do something
break;
case dialog2:
//do something else
break
}
});
This way on the other hand requires me to have a load of switch cases for each event I'm interested in capturing.
Would writing a wrapping plugin be a good idea here? A plugin that forces you to give an id
to each dialog. It would then retrigger each event with the id
as prefix or suffix. Opening #dialog1
would for example trigger the custom event dialog1open
.
Ideas or concrete solutions would be appreciated here
Edit: A crucial thing I did not mention is that I have observers that the subject (Like #dialog1
and #dialog2
) does not know of. This must be taken into consideration.