Skip to content

Instantly share code, notes, and snippets.

@vlado
Created September 19, 2012 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlado/3750538 to your computer and use it in GitHub Desktop.
Save vlado/3750538 to your computer and use it in GitHub Desktop.
Example js organization code
// ================================================
// We can put everything under "bd" namespace
// ================================================
window.bd = {};
// define some util functions and/or classes under util namespace
bd.util = {};
bd.util.toFloat = function(obj) {
return parseFloat(obj);
};
// or some directly on bd namespace
bd.log = function(something) {
if (console)
console.log(something)
}
// we define some view helpers used on multiple (all) pages
bd.viewHelpers = {};
bd.viewHelpers.CustomScrollbars = new Class({
initialize: function() {
// code to show custom scrollbars
}
});
// we put all view specific classes under bd.views namespace
bd.views = {
beforeFilter: function() {
new bd.viewHelpers.CustomScrollbars();
},
afterFilter: function() {
// something to do after view init (this filters could be developed to be very powerfull if needed)
}
};
// we define new class for each view
bd.views.Login = new Class({
initialize: function() {
this.alertLogin();
bd.util.toFloat("123.45");
},
alertLogin: function() {
alert('Login')
}
// ... more methods ...
});
bd.views.Home = new Class({
initialize: function() {
this.alertHome();
},
alertHome: function() {
alert('Home')
}
// ... more methods ...
});
// we add data-view attribute to body tag <body data-view='Login'> pick it on ready and use it to instantize right class
window.addEvent('domready', function() {
bd.view = $$('body').pick().getAttribute('data-view');
bd.views.beforeFilter(); // other approach for this filters could be to define some Base view and have all views extend from it
new bd.views[bd.view]();
bd.views.afterFilter();
});
// ================================================
// OR we can define everything globally
// ================================================
// (I would prefer to use bd namespace at least for everything so we are 100% sure there will be no collision with other libraries)
LoginView = new Class({
initialize: function() {
this.alertLogin();
bd.util.toFloat("123.45");
},
alertLogin: function() {
alert('LoginView')
}
});
window.addEvent('domready', function() {
var view = $$('body').pick().getAttribute('data-view');
new window[view+'View']();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment