Cleaning Up Our Modal Dialog Code
Learn how to clean up our code using a dedicated region to manage the modal dialogs.
We'll cover the following...
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:
Press + to interact
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 view using listenTo
and execute the closeDialog
function if it gets triggered in line 15. This will allow us to empty the dialog region from the view by ...