Drawbacks of the namespacing pattern

• Reliance on a single global variable to be the application’s global. In the namespacing pattern, there is no way to have two versions of the same application or library run on the same page, because they both need the same global symbol name, for example, MYAPP.

• Long,  dotted  names  to  type  and  resolve  at  runtime,  for  example, MYAPP.utilities.array.

A Global Constructor

Using the sandbox will look like this:

new Sandbox(function (box) {

    // your code here...

});

The  object  box will  be  like  MYAPP in  the  namespacing  example—it  will  have  all  the library functionality you need to make your code work.

Sandbox(['ajax', 'event'], function (box) {

    // console.log(box);

}); 

module names are passed as individual argument

Sandbox('ajax', 'dom', function (box) {

    // console.log(box);

}); 

when no modules are passed, the sandbox will assume '*'.

Sandbox('*', function (box) {

    // console.log(box);

});

Sandbox(function (box) {

    // console.log(box);

}); 

protect the global namespace by having your code wrapped into callback functions.

Sandbox('dom', 'event', function (box) {

    // work with dom and event

    Sandbox('ajax', function (box) {

        // another sandboxed "box" object

        // this "box" is not the same as

        // the "box" outside this function

        //...

        // done with Ajax

    });

    // no trace of Ajax module here

}); 

Adding Modules

Sandbox.modules = {};

Sandbox.modules.dom = function (box) {

    box.getElement = function () {};

    box.getStyle = function () {};

    box.foo = "bar";

};

Sandbox.modules.event = function (box) {

    // access to the Sandbox prototype if needed:

    // box.constructor.prototype.m = "mmm";

    box.attachEvent = function () {};

    box.dettachEvent = function () {};

};

Sandbox.modules.ajax = function (box) {

    box.makeRequest = function () {};

    box.getResponse = function () {};

};

Implementing the Constructor

function Sandbox() {

    // turning arguments into an array

    var args = Array.prototype.slice.call(arguments),

        // the last argument is the callback

        callback = args.pop(),

        // modules can be passed as an array or as individual parameters

        modules = (args[0] && typeof args[0] === "string") ? args : args[0],

        i;

    // make sure the function is called

    // as a constructor

    if (!(this instanceof Sandbox)) {

        return new Sandbox(modules, callback);

    }

    // add properties to `this` as needed:

    this.a = 1;

    this.b = 2;

    // now add modules to the core `this` object

    // no modules or "*" both mean "use all modules"

    if (!modules || modules === '*') {

        modules = [];

        for (i in Sandbox.modules) {

            if (Sandbox.modules.hasOwnProperty(i)) {

                modules.push(i);

                // Sandbox.modules[i](this);

            }

        }

    }

    // initialize the required modules (Kaibo: The code below in yellowcan be omitted by the code in yellow above to avoid the 2nd loop)

    for (i = 0; i < modules.length; i += 1) {

        Sandbox.modules[modules[i]](this);

    }

    // call the callback

    callback(this);

}

// any prototype properties as needed

Sandbox.prototype = {

    name: "My Application",

    version: "1.0",

    getName: function () {

        return this.name;

    }

};

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 5.5 Sandbox Pattern的更多相关文章

  1. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  2. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  3. JavaScript Patterns 5.1 Namespace Pattern

    global namespace object // global object var MYAPP = {}; // constructors MYAPP.Parent = function() { ...

  4. JavaScript Patterns 4.2 Callback Pattern

    function writeCode(callback) { // do something... callback(); // ... } function introduceBugs() { // ...

  5. JavaScript Patterns 2.6 switch Pattern

    Principle • Aligning each case with switch(an exception to the curly braces indentation rule). • Ind ...

  6. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  7. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  8. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  9. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

随机推荐

  1. c++控制台程序实现定时器

    #include "stdafx.h" #include <iostream> #include <Windows.h> using namespace s ...

  2. android app自动化测试之UIAutomator

    一.UIAutomator Android自动化测试工具有很多,但是要免费.易上手,本人觉得就直接使用Eclipse自带的UIAutomator就不错.测试人员无需跟开发要代码信息,只要手机上有安装之 ...

  3. ASP.NET MVC 网站开发总结(五)——Ajax异步提交表单之检查验证码

    首先提出一个问题:在做网站开发的时候,用到了验证码来防止恶意提交表单,那么要如何实现当验证码错误时,只是刷新一下验证码,而其它填写的信息不改变? 先说一下为什么有这个需求:以提交注册信息页面为例,一般 ...

  4. mysql ,为什么一张表的varchar关联另一张表varchar执行失败的一个原因

    CONSTRAINT `orderdts_ibfk_2` FOREIGN KEY (`address`) REFERENCES `test列` (`address`) 很可能的原因是另一张表的test ...

  5. Spring中常用的连接池配置

    首先,我们准备Jdbc属性文件 jdbc.properties,用于保存连接数据库的信息,利于我们在配置文件中的使用 jdbc.driver=com.mysql.jdbc.Driver jdbc.ur ...

  6. [小北De编程手记] : Lesson 04 玩转 xUnit.Net 之 Fixture(下)

    上一篇文章<[小北De编程手记] : Lesson 03 玩转 xUnit.Net 之 Fixture(上)>向大家介绍了xUnit.Net 共享数据的方式.Test Case的构造函数 ...

  7. tomcat jdk servlet websocket版本对应关系

    最近在考虑公司主要基础三方库版本统一和升级的问题,特看了下tomcat jdk servlet websocket版本的对应关系,如下:

  8. jQuery中的事件与动画 (你的明天Via Via)

    众所周知,页面在加载时,会触发load事件:当用户单击某个按钮时,会触发该按钮的click事件. 这些事件就像日常生活中,人们按下开关,灯就亮了(或者灭了),往游戏机里投入游戏币就可以启动游戏一样, ...

  9. 使用 WordPress 插件模板开发高质量插件

    WordPress 插件样板是标准化的,有组织的,面向对象的基础,用于构建高品质的 WordPress 插件.样板遵循编码标准和文件标准,所以你不必自己学习这些,根据注释编写代码即可. 官方网站    ...

  10. T3 - 构建大型 Web 应用的 JavaScript 框架

    T3 是一个用于构建大型 Web 应用程序的客户端 JavaScript 框架.T3 和大多数的 JavaScript 框架不同.它的意思是一小部分的整体架构,它允许你建立可扩展的客户端代码.T3 应 ...