Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Quick intro to Javascript Modules

If you're looking for something in depth, I suggest http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

var SomeMarionetteApp = (function(my, $, _, backbone, Marionette, bootstrap, common) {
    my.App = Marionette.Application.extend({
        initialize: function(options){
            var self = this;

            this.views = {};
            this.collections = {};
            this.models = {};

            this.views.topnav = new Chartest.View.TopNav();

            this.views.topnav.render();
        }
    });

    my.View = {};
    my.Model = {};
    my.Collection = {};
    my.Template = {
        nav_header: "#tmpl_nav_header"
    };

    my.View.TopNav = Marionette.ItemView.extend({
        el: "#top_nav",
        template: my.Template.nav_header
    });

    return my;
}(SomeMarionetteApp || {}, $, _, Backbone, Marionette, common));

var SomeMarionetteApp describes a global name that you're defining.

}(SomeMarionetteApp || {}, $, _, Backbone, Marionette, common)); describes what's available to the function you're defining. The first argument SomeMarionetteApp || {} defines what you're exporting. If it doesn't exist in the global space it's defined as '{}', an empty object.

(function(my, $, _, backbone, Marionette, bootstrap, common) { describes the arguments passed into the function from the bottom line. Notice that the first argument is my, this is similar to this in most other JavaScript functions. It refers to what you're expoirting (on the return my;) line.

From there you define sub-objects and functions in the body of the function. You could split these out into seperate files if things grow too large, for example if I wanted to put my views in a different file it'd look like this:

var SomeMarionetteApp.View = (function(my, $, _, backbone, Marionette, bootstrap, common) {
  my.HeaderView = Marionette.ItemView.extend{
    el: "#header",
    template: "#tmpl_header_view"
  });
  
  return my;
}(SomeMarionetteApp || {}, $, _, Backbone, Marionette, common));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.