Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #9 Module Design

$
0
0

In issue #8 we learned how we could create a framework with a closure and return object. We can extend this template for creating modules for a previously defined framework or parent module.

By modifying the framework template a little bit, we can create a module that plugs into another object.

(function (parent){
     var name = 'module';
     var version = 1;
     if (!parent[name] || parent[name].version < version) {
          parent[name] = function () {
               // Private members
               return {
                    version: version
                    // public members
               };
           }();
     }
}(Framework));

In the example above, we create a module with a certain name and version. We check if the parent (in this case Framework) doesn’t contain the module, if it does… we check if this is a newer version. Note that you can add your own versioning system to this declaration of modules, this is merely an example.

Instead of passing along the Framework, we could feed the closure Framework.module. The code will stay the same, but instead of creating a module on framework (with checks), we will create a sub-module.

By using a simple pattern (closure + return object) we are able to create frameworks, modules, plugging them into frameworks or other models. Also, we can hide functions/variables from outsiders and we choose explicitly which functions and variables are available.



Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images