Created
January 21, 2015 18:29
-
-
Save RohitRox/ff2b490e4dfa4e7849c4 to your computer and use it in GitHub Desktop.
One way to organize Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var module = new function() { | |
var define, definitions, require; | |
definitions = {}; | |
define = function(moduleName, dependencies, fn) { | |
if (fn === undefined) { | |
fn = dependencies; | |
dependencies = []; | |
} | |
definitions[moduleName] = { | |
dependencies: dependencies, | |
fn: fn, | |
id: moduleName | |
}; | |
return definitions[moduleName]; | |
}; | |
isFunction = function(param) { | |
return (typeof(param) === "function") | |
} | |
showDefinitions = function() { | |
console.log(definitions); | |
} | |
resolve = function(def) { | |
definition = definitions[def]; | |
if (!isFunction(definition.fn)) { | |
return definition.fn | |
} | |
deps = [] | |
if (definition.dependencies.length > 0) { | |
definition.dependencies.forEach(function(dependency) { | |
d = definitions[dependency] | |
deps.push(d.fn) | |
}); | |
} | |
fn = deps.length < 1 ? definition.fn : definition.fn.apply(undefined, deps) | |
return fn; | |
} | |
require = function(moduleName, callback) { | |
r = resolve(moduleName) | |
if (callback !== undefined) { | |
callback(r) | |
} | |
return r; | |
}; | |
return { | |
define: define, | |
require: require, | |
showDefinitions: showDefinitions | |
}; | |
}; | |
// Examples | |
module.define("$", jQuery); | |
module.define('user', { | |
email: "hello@mail.com", | |
name: "kelly kelly" | |
}); | |
module.require('user', function(user){ | |
console.log("Callbacked : ", user, "is now available") | |
}); | |
module.define('tracker', { | |
track: function(options) { | |
console.log(options, " TRACKED.") | |
}, | |
trackUser: function(user) { | |
console.log("NOW TRACKING USER", user.name) | |
} | |
}); | |
module.define('main', ["user", "tracker", "$"], function(user, tracker, $) { | |
function init() { | |
console.log("$$$$", $) | |
tracker.trackUser(user); | |
} | |
return { | |
init: init | |
} | |
}); | |
module.require('main').init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment