Skip to content

Instantly share code, notes, and snippets.

View mcavaliere's full-sized avatar

Mike Cavaliere mcavaliere

View GitHub Profile
// /javascripts/myapp/ui/fancyslider.js
MyApp.ns("MyApp.UI.FancySlider");
MyApp.UI.FancySlider = function() {
// ...
};
var MyApp = {};
MyApp.namespace = function() {
var ln = arguments.length, i, value, split, x, xln, parts, object;
for (i = 0; i < ln; i++) {
value = arguments[i];
parts = value.split(".");
object = window[parts[0]] = Object(window[parts[0]]);
// Top level. All reusable code goes somewhere under this main object.
var MyApp = {};
// Widgets, and any components that manipulate the DOM.
MyApp.UI = {};
// Classes that have reusable logic or calculation.
MyApp.Lib = {};
// Custom code that works with external javascript libraries in a reusable way.
$.MyCompany = {
Widgets: {
data1: 123,
func1: function() {}
},
HtmlUtils: {
data1: 123,
func1: function() {}
}
};
// /javascripts/mycompany.js
var MyCompany = {};
// /javascripts/mycompany/widgets
MyCompany.Widgets = {};
MyCompany.Widgets.data1 = 123;
MyCompany.Widgets.func1 = function() {};
// /javascripts/mycompany/htmlutils.js
MyCompany.HtmlUtils = {};
var MyCompany = {
Widgets: {
data1: 123,
func1: function() {}
},
HtmlUtils: {
data1: 123,
func1: function() {}
}
}
MyNamespace.myString;
MyNamespace.myInt;
MyNamespace.myFunc();
var MyNamespace = {
myString: "someString",
myInt: 123,
myFunc: function() {
return this.myString + " " + this.myInt;
}
};
// Less Coupled
var CountrySelectClass = function() {
var countriesIveBeenTo = {
'BE': 'Belgium',
'CR': 'Costa Rica',
'IT': 'Italy',
'US': 'United States of America',
'UK': 'United Kingdom'
};
// Heavily Coupled
$(function() {
$(document.body).append( $('<select id="countries"></select>') );
var countriesIveBeenTo = {
'BE': 'Belgium',
'CR': 'Costa Rica',
'IT': 'Italy',
'US': 'United States of America',
'UK': 'United Kingdom'