|
Modules
Panda JS' Module Implementation
IntroductionPanda JS' modules are inspired by the Modular JS library. The code and documentation there is quite good so be sure to check it out. Core ConceptsPanda JS modules provide a simple mechanism for well structured, sharable code modules without modifying any external namespaces (though this option exists). This works especially well for large applications which are broken into smaller components, however modules are quite nice on smaller page-level applications as well. Module NamespacesNote: For a deeper discussion on namespaces, please see the Namespaces documentation. This also includes much simpler syntax for exposing namespaces using the panda.namespace utility method. JavaScript is at a point now where most professional developers are namespace-aware and have begun writing well organized code without polluting the global object. A traditional technique for implementing namespaces in JavaScript requires defining objects like so: var foo = {
name : 'foo'
};Likewise, to create a nested namespace, you simply create another object: foo.bar = {
name : 'bar'
};However this becomes problematic if you have code spread across multiple files. If foo does not exist prior to you trying to set a value in foo.bar, you get an error. No matter how deeply you define your module's namespace, Panda will insure that your code works as intended. panda('foo.bar.baz.bif').expose();Sharing and Privacy in ModulesThe typical way of achieving private members in JavaScript is by using Douglas Crockford's Module Pattern: var foo = function () {
var secret = 'This is my secret';
return {
getSecret : function () {
return secret;
}
};
}();By default, no modules are externally exposed in Panda. You must explicitly call the module's expose method which, as you may have guessed, exposes the object. Although it is a more traditional approach, exposing your code isn't necessary at all in Panda. Consider the following code: panda('foo').define(function () {
var secret = 'This is foo secret';
return {
getSecret : function () {
return secret;
}
};
});We've now created a completely private module named foo. Now any other modules we define can use this module as a shared resource. panda('bar').use('foo').define(function(foo) {
var mySecret = foo.getSecret().replace(/foo/, 'bar');
return {
getSecret : function () {
return secret;
}
}
});
|