Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created November 17, 2011 16:19
Show Gist options
  • Save mxriverlynn/1373574 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1373574 to your computer and use it in GitHub Desktop.
// an immediate function
(function(){
// code goes here
})();
// a module with a public API returned
var MyModule = (function(){
// this variable is private
var privateVariable = "I'm scoped to the module's internals!";
// object to return as a public API
var myAPI = {};
// a public function on the API
myAPI.somePublicFunction = function(){
alert("You called: MyModule.somePublicFunction()");
};
// return the public API so it can be accessed
return myAPI;
})();
var MyModule = (function($, Backbone){
// use $ here. it's scoped locally, now.
var someEl = $("#someEl");
// use Backbone here. it's scoped locally, now.
var MyView = Backbone.View.extend({
// ...
});
})(jQuery, Backbone);
MyModule = (function(MyApp, Backbone){
var MyView = Backbone.View.extend({
// ...
};
MyApp.addInitializer(function(){
new MyView({
// ...
}).render();
});
})(MyApp, Backbone);
MyApp = (function(_){
var myApp = {};
var initializers = [];
myApp.addInitializer = function(callback){
var initializer = {
obj: this,
callback: callback
}
initializers.push(initializer);
};
myApp.initialize(){
_.each(initializers, function(initializer){
initializer.callback.call(initializer.obj);
});
};
})(_);
MyApp = (function(_, Backbone){
var myApp = {};
// the event aggregator
myApp.vent = _.extend({}, Backbone.Events);
// the other app initialization code ...
return myApp;
})(_, Backbone);
MyModule = (function(MyApp, Backbone){
var MyView = Backbone.View.extend({
initialize: function(){
MyApp.bind("some:event", this.someCallback, this);
},
someCallback: function(){
alert("I'm Doing Stuff!!!");
}
});
// ... other code, including MyApp.addInitializer
})(MyApp, Backbone);
AnotherModule = (function(MyApp){
var anotherModule = {};
anotherModule.SomeFunction = function(){
MyApp.trigger("some:event");
}
return anotherModule;
});
// kick it all off and show the alert box
$(function(){
MyApp.initialize();
AnotherModule.SomeFunction();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment