I’m trying to write a basic dialog box. I want to be able to specify a link element which will launch a dialog box when clicked.
I’n specifying this behavior using data attributes in the dialog boxes HTML:
<a id="launch-dialog" href="#"></a>
<div class="dialog" data-behavior="dialog" data-trigger="#launch-dialog">
<!-- dialog html -->
</div>
$(function(){
$("[data-behavior='dialog']").dialog();
});
The actual jQuery extension is the part I’m having trouble with though. Either the 'dopen' event isn’t being triggered on the body correctly or else the event binding isn’t being set up correctly. The click event on the data-trigger is definitely firing and being listened to though. Any ideas why I never see the “open detected” log?
(function($) {
var methods = {
init: function(options) {
if (this.data('trigger')) {
// Add an event listener which causes the dialog to
// open when the correct link is clicked.
$(this.data('trigger')).on('click', function(e) {
e.preventDefault();
// Trigger a global dialog open event which the dialog can subscribe to.
$('body').trigger('dopen');
});
}
},
// Various other methods not shown.
};
$.fn.dialog = function(method) {
// Method handling code not shown...
// Add handlers for custom events triggered on the body element.
$('body').bind('dopen', function(e) {
// This never happns:
console.log("Open detected");
});
};
})(jQuery);
I accidentally didn’t give enough information in my question to be able to solve the problem.
Where I have
in the question code, the real code has the following:
As you can see, that snippet has three possible paths:
Control flow was getting short-cut in these paths and wasn’t reaching the line where I try to bind a listener. Of course, an unbound listener can never be fired.
The solution was to move the binding up into the initialization method: