Thursday, April 26, 2012

"JavaScript Patterns" Sandbox Pattern Correction

More from the JS world; I've been evaluating some ways to simplify the ponderous namespace typing in my javascript framework. It would appear, at this point, that the leading way to do this is by using the Sandbox pattern. As I understand it, the pattern is heavily used by the Yahoo YUI guys. It provides some other interesting capability as well, such as being able to create separate "app domains" as it were, that use different modules based on what you feed the Sandbox constructor. These different sandbox domains can be nested, etc. It's truly a plumbing pattern that seems to have a lot of potential to make your app more flexible and modular, as well as making the code easier to write/read.

 So far, I get it, and I believe it will be useful, but I'm still evaluating.

 I discovered that a reference implementation for the Sandbox pattern is in a book I already have; JavaScript Patterns. However, the reference pattern allows for feeding the desired modules for a given sandbox instance by a list of names, an array, or a '*' (meaning, use all available modules that have been registered with the Sandbox's static "modules" object literal).

 The problem is in the check that looks to see if you used "*".
if ( !modules || modules === '*' ) {
        modules = [ ];
        for ( i in Sandbox.modules ) {
            if ( Sandbox.modules.hasOwnProperty ( i ) ) {
                modules.push ( i );
            }
        }
    }
This causes an error, because the check will never evaluate to true; modules will never be as type "string", because earlier on it's typed as an array. So 'all available modules' will never get added to the Sandbox instance.

 The fix; add 'toString ( )' to the check (it makes sense, you're using absolute equality against '*', which is a string):
if ( !modules || modules.toString ( ) === '*' ) {
        modules = [ ];
        for ( i in Sandbox.modules ) {
            if ( Sandbox.modules.hasOwnProperty ( i ) ) {
                modules.push ( i );
            }
        }
    }
And the check will proceed as intended.

 As always, thanks for visiting.

No comments:

Post a Comment