1+ <!doctype html>
2+ < html lang ="en ">
3+ < head >
4+ < title > JavaScript Patterns</ title >
5+ < meta charset ="utf-8 ">
6+ </ head >
7+ < body >
8+ < script >
9+ /* Title: Sandbox Pattern
10+ Description:
11+ */
12+
13+ function Sandbox ( ) {
14+ // turning arguments into an array
15+ var args = Array . prototype . slice . call ( arguments ) ,
16+ // the last argument is the callback
17+ callback = args . pop ( ) ,
18+ // modules can be passed as an array or as individual parameters
19+ modules = ( args [ 0 ] && typeof args [ 0 ] === "string" ) ? args : args [ 0 ] ,
20+ i ;
21+
22+ // make sure the function is called
23+ // as a constructor
24+ if ( ! ( this instanceof Sandbox ) ) {
25+ return new Sandbox ( modules , callback ) ;
26+ }
27+
28+ // add properties to `this` as needed:
29+ this . a = 1 ;
30+ this . b = 2 ;
31+
32+ // now add modules to the core `this` object
33+ // no modules or "*" both mean "use all modules"
34+ if ( ! modules || modules == '*' ) {
35+ modules = [ ] ;
36+ for ( i in Sandbox . modules ) {
37+ if ( Sandbox . modules . hasOwnProperty ( i ) ) {
38+ modules . push ( i ) ;
39+ }
40+ }
41+ }
42+
43+ // initialize the required modules
44+ for ( i = 0 ; i < modules . length ; i += 1 ) {
45+ Sandbox . modules [ modules [ i ] ] ( this ) ;
46+ }
47+
48+ // call the callback
49+ callback ( this ) ;
50+ }
51+
52+ // any prototype properties as needed
53+ Sandbox . prototype = {
54+ name : "My Application" ,
55+ version : "1.0" ,
56+ getName : function ( ) {
57+ return this . name ;
58+ }
59+ } ;
60+
61+ Sandbox . modules = { } ;
62+
63+ Sandbox . modules . dom = function ( box ) {
64+ box . getElement = function ( ) { } ;
65+ box . getStyle = function ( ) { } ;
66+ box . foo = "bar" ;
67+ } ;
68+
69+ Sandbox . modules . event = function ( box ) {
70+ // access to the Sandbox prototype if needed:
71+ // box.constructor.prototype.m = "mmm";
72+ box . attachEvent = function ( ) { } ;
73+ box . dettachEvent = function ( ) { } ;
74+ } ;
75+
76+ Sandbox . modules . ajax = function ( box ) {
77+ box . makeRequest = function ( ) { } ;
78+ box . getResponse = function ( ) { } ;
79+ } ;
80+
81+
82+ // how to use
83+ Sandbox ( [ 'ajax' , 'event' ] , function ( box ) {
84+ // console.log(box);
85+ } ) ;
86+
87+ Sandbox ( 'ajax' , 'dom' , function ( box ) {
88+ // console.log(box);
89+ } ) ;
90+
91+ Sandbox ( '*' , function ( box ) {
92+ // console.log(box);
93+ } ) ;
94+ </ script >
95+ </ body >
96+ </ html >
0 commit comments