Delivering Modular JavaScript to Mobile Clients
Author Alex Ciminian
2012-01-09 00:50
Author Alex Ciminian
2012-01-09 00:50
The module pattern is widely used because [...] helps organize your code as it grows. [...] the module pattern provides the tools to create self-contained decoupled pieces of code , which can be treated as black boxes of functionality and added, replaced, or removed [...].
define('myModule',
['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});
define(function ( require ) {
var isReady = false, foobar;
// note the inline require within our module definition
require(['foo', 'bar'], function (foo, bar) {
isReady = true;
foobar = foo() + bar();
});
// we can still return a module
return {
isReady: isReady,
foobar: foobar
};
});
Alex MacCaw: JavaScript Web Applications
Addy Osmani: Writing Modular JavaScript