Now I would like to introduce the concept of a framework singleton that avoids clutter in the global namespace and simplifies management of JavaScript codebase.
This singleton must provide the following piece of functionality -
- Contained namespace
- Window onload stack
- Initialization method to allow modular extensions to the framework
- Public, Global attributes (such as a debugging flag, a DOM signature, etc)
- Global helpers, added as necessary
Skip the steps & get straight to the final product
Let's start:
The Global FRAMEWORK node
In my first post, I described two patterns, (a) create a singleton and (b) create a 'base' object like a java pojo. Applying the first pattern, creating a singleton, we essentially initialize the framework like so --Note: FRAMEWORK is in the global ns in the example above. I would recommend, like most library/api conventions, you keep it short since you'll be referencing it.
The above example satisfies our first goal, containing the namespace so that any variables defined with the 'var' modifier, will be treated private to FRAMEWORK; allowing us to specify attributes that can only be overridden if public methods exist to access them.
FRAMEWORK's window onload stack
Often times events or utility init's require a loaded DOM. Rather than initializing the function immediately, we can store the init functions in local memory in an array and piggy back on a framework to perform the window onload event. This ensures a synchronous initialization of extended utils.The array, readyFunctionStack is init'd as an array literal with the initFramework function as the internal init function. The initFramework() function is private, which ensures that the init method cannot be modified. The p.ready is a public method, which has a timer within it to display how long the framework initialization takes to init all the functions pushed to the stack.
The p.ready function is referenced as FRAMEWORK.ready, and should be passed onto document ready (window load) methods, like in jQuery: jQuery(document).ready(FRAMEWORK.ready), after the code for FRAMEWORK.
No comments:
Post a Comment