Search⌘ K
AI Features

Cleaning Up Our Modal Dialog Code

Explore how to streamline your Marionette.js modal dialogs by using a dedicated dialog region to handle showing and closing views. Understand event listening for dialog closure, region configuration, and how to adapt views and controller code for better encapsulation and maintenance.

Now that we’re using modal dialogs in multiple places, it’s time to clean up our code by using a dedicated region to manage them. This region will be responsible for calling the dialog function to turn a view into a modal window and remove its DOM element when the dialog is closed, among other responsibilities.

Configuring existing dialogue regions

To achieve this, we’re simply going to make our existing dialog region automatically configure any view that it shows:

Node.js
ContactManager.on("before:start", function(){
var RegionContainer = Marionette.LayoutView.extend({
// edited for brevity
});
ContactManager.regions = new RegionContainer();
ContactManager.regions.dialog.onShow = function(view){
var self = this;
var closeDialog = function(){
self.stopListening();
self.empty();
self.$el.dialog("destroy");
};
this.listenTo(view, "dialog:close", closeDialog);
this.$el.dialog({
modal: true,
title: view.title,
width: "auto",
close: function(e, ui){
closeDialog();
}
});
};
});

We listen for the “dialog:close” event on our ...