Skip to content

Instantly share code, notes, and snippets.

@Amitesh
Created July 11, 2012 10:26
Show Gist options
  • Save Amitesh/3089510 to your computer and use it in GitHub Desktop.
Save Amitesh/3089510 to your computer and use it in GitHub Desktop.
New App JS bootup scripts
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/**
* Module for SampleWebApp Application
* @author : Amitesh Kumar
*
*/
( function( $ ){
//var globalInfo = '#global-info';
// global namespace
SampleWebApp = ( typeof SampleWebApp == 'undefined' ) ? {} : SampleWebApp;
// global namespace
SampleWebApp.common = ( typeof SampleWebApp.common == 'undefined' ) ? {} : SampleWebApp.common;
SampleWebApp.common = {
init : function(){
$('.dropdown-toggle').dropdown()
$(".alert").alert();
}
};
SampleWebApp.app = SampleWebApp.app || {};
SampleWebApp.app.env = function(){
var env = null;
return {
setEnv : function( env ){
this.env = env;
},
getEnv : function(){
return this.env;
},
isDevelopment : function(){
return this.env === "development"
},
isStaging : function(){
return this.env === "staging"
},
isProduction : function(){
return this.env === "production"
}
}
}();
//========================================================
// global namespace
SampleWebApp.home = ( typeof SampleWebApp.home == 'undefined' ) ? {} : SampleWebApp.home;
/**
* Functions used in page Home controller
*/
SampleWebApp.home = {
init : function(){
},
index : function(){
}
};
//========================================================
})( $ );
$(document).ready(function(){
SampleWebApp.common.init();
})
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
// Load basic files.
//= require namespace
//= require boot
//= require app
/**
* Utility module which simplifies/streamlines the JavaScript code initialization on page.
* The purpose of this module is to free the developers from worrying about which code to
* execute in which page. We often see a pattern where devs tend to add lots of $().ready()
* callbacks to execute code when the page is loaded, as these days we combine multiple
* files together, so this way we essentially end up having multiple $().ready callbacks in
* one bundle which gets executed in each page, even in pages where they are not supposed to
* be executed, to prevent errors we end up putting some sort of the if() block to see whether
* this page is the right place for that code.
*
* The idea here is to avoid those scenarios and provide a common place from where one will
* initialize JavaScript. This is based on the convention that the <body> tag will have two
* HTML5 data-* attributes called "data-controller" and "data-action". As a dev you define
* an Object literal in the name of the controller and add methods in that object literal
* representing actions.
*
* CAUTION: To prevent this module to become bloated, put your actual logic in a separate file
* and only put the initialize code in this module in appropriate place, please do not put
* your business logic here :-).
*
*
* @author: Arnab Chakraborty ( [email protected] )
* @author: Amitesh Kumar ( [email protected] )
*
*/
( function (W) {
// Application Boot procedure code
SampleWebApp.Boot = {
// ================ Prohihbited teritorry :-) =================================
/**
* Utility method to execute module specific code in a seamless manner
* this method is being used internally, don't call this method from
* outside the module.
*
* @private
* @param controller
* @param action
*/
_exec: function ( controller, action ) {
controller || ( controller = 'common' );
action || ( action = 'init' );
var ns = SampleWebApp.Boot,
actions,
// inner function to execute the
// target method
execute = function ( ctlr, axon ) {
// debug.log( ctlr, axon );
var fn = ( ns[ctlr] || {} )[axon];
if( $.isFunction( fn ) ) {
try {
// set 'this' as Junction.Boot
fn.call( SampleWebApp.Boot );
} catch( ex ) {
// @TODO handle errors gracefully
console.error( ex.message );
}
}
};
// this switch case may be unnecessary
// I've put it here to execute groups. Specifically to execute multiple groups
// I wanted to have the ability to do the following:
// _exec( 'group', 'authenticate', 'showRelatedBooks', 'displayBookPrice' )
switch ( controller.toLowerCase() ) {
case 'group':
// convert the arguments object to real array
actions = _.toArray( arguments ).slice(1);
$.each( actions, function ( action ) {
execute( controller, action );
} );
break;
default:
execute( controller, action );
}
},
// ====================================== End ============================================
/**
* The following object literal does not represent a controller, instead it's a general name
* which denotes that whatever we put in the init() method below will be executed
* in all the pages, across the site.
*/
common: {
/**
* Method to initialize the Junction Application, it handles instantiating
* all required modules as well as other things.
*
* @param data - Initial set of data required for the application to start working properly
*/
init: function ( data ) {
}
},
/**
* Group is an interesting thing, it is not automatically executed and it does not have
* any init() method by default because it does not make sense. This again is not the name
* of a controller (hopefully we'll not introduce groups in future, but you never know
* because 'specs change' :-) ). Group is introduced to handle the situations where we
* need to do something for a set of pages but not for all, so we group the identical
* methods together here.
*/
group: {
// grouped tasks for authentication can be called
// from multiple places
auth: function () {
}
},
/**
* =========================================================================
* Each controller represents an object literal here, which contains
* an init() method and separate methods for each action. The init()
* method is controller wide code, only put code which are going to
* to be executed in all the pages under that controller. For example:
*
* /accounts
* /accounts/settings
* /accounts/social
*
* If you put an init() method in accounts {} literal, then that method will
* be executed in all those pages.
* =========================================================================
*/
home: {
init: function () {
//new SampleWebApp.Apps();
}
}
}
// boot up the app when ready
// yayyy we only have one $().ready, so coool
// For the following to work you need to add the following code to your <body> tag in the HTML
// <body data-controller="<%= controller_namne %>" data-action="<%= action_name %>">
$( document ).ready( function boot() {
var body = $( document.body ),
// the following two lines assume that you are running
action = body.data('action'),
controller = body.data('controller'),
appEnv = body.data('app-env');
SampleWebApp.app.env.setEnv( appEnv );
SampleWebApp.Boot._exec(); // execute site wide code
SampleWebApp.Boot._exec( controller ); // execute controller wide code
SampleWebApp.Boot._exec( controller, action ); // execute action specific code
} );
} )(this);
// SampleWebApp application the main namespace
this.SampleWebApp || (SampleWebApp = {});
// utility methods to be used across application
/**
* Returns the authenticity tokens required by rails
*/
SampleWebApp.getAuthTokenMap = function () {
var map = {};
map[$( 'meta[name=csrf-param]' ).attr( 'content' )] = $( 'meta[name=csrf-token]' ).attr( 'content' );
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment