Last Updated: February 25, 2016
·
1.225K
· headwinds

MarionetteJS View Controller as a RequireJS module

This is my first pro tip posting so I'm just kicking the tires here...

I ran into the common problem in Backbone where my views were not getting cleaned up after I attempted to remove them; thus creating memory leak zombies.

This code sample is a refactoring of Derick's excellent post and 99% credit goes to him - I'll take the 1% promoter credit for putting it together in Requirejs and adding a few arguments which I like to optionally pass into each render.

define([
'jquery',
'underscore', 
'backbone',
'marionette'
], function($, _, Backbone, Marionette) {

var AppViewController = Backbone.Marionette.Controller.extend({

    currentView: null,

    showView: function(view, bSelfRender, stateStr ) {

        var that = this;

        if (that.currentView) {

            console.debug("AppViewController - view removed");

            that.currentView.remove();
            that.currentView.unbind();
            that.currentView = null;
        }

        that.currentView = view;

        if (!bSelfRender) that.currentView.render( stateStr );
    }

});

return AppViewController;

});

Now before I want to display any view, I'll use a view controller first to manage this process.

var viewController = new AppViewController(); 

var oneView = new OneView( { model: mainModel });
var twoView = new TwoView( { model: mainModel });

viewController.showView(oneView, false, "contentCreation"); 

After I'm finished with this view, I'll use the viewController again to transition to the next view ( or back to a fresh version of the first view) knowing that first view is safely cleaned up

viewController.showView(twoView, false, "contentCreation");