Created
July 30, 2011 01:33
-
-
Save benekastah/1115086 to your computer and use it in GitHub Desktop.
Target syntax for client-side javascript module system
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
<html> | |
<head> | |
<title>Modules!</title> | |
<script src="module_source.js"></script> | |
<script> | |
// `require` takes as many scripts as you want as input. Leave off the .js if you want. | |
// The last argument is the callback for when all the scripts in the list are done loading | |
require("path/to/jquery", "path/to/dependency", "etc/etc/etc", function () { | |
$(function () { | |
// do stuff when dom is ready | |
}); | |
}); | |
// Notice when loading a module you don't have to say `some.object = require('some/script')` | |
require("index", function () { | |
appName.index.initialize(); | |
}); | |
</script> | |
</head> | |
<body> | |
<h1>Something</h1> | |
</body> | |
</html> |
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
// First argument is namespace | |
// Second argument is function with contents of entire file (it is run immediately) | |
// Because the entire contents of the file are in this function, we don't have stray global variables running around. Encapsulation FTW! | |
module("appName.index", function (exports) { | |
// the namespace object is bound to the argument coming into the function, and also to `this` | |
// the argument coming in is more handy for the contents of functions within this function where `this` doesn't bind properly | |
exports.initialize = function () { | |
doSomethingCool() | |
}; | |
function doSomethingCool() { | |
console.log("Something cool."); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment