JavaScript Patterns 5.5 Sandbox Pattern
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的更多相关文章
- JavaScript Patterns 5.8 Chaining Pattern
Chaining Pattern - Call methods on an object one after the other without assigning the return values ...
- JavaScript Patterns 5.4 Module Pattern
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...
- JavaScript Patterns 5.1 Namespace Pattern
global namespace object // global object var MYAPP = {}; // constructors MYAPP.Parent = function() { ...
- JavaScript Patterns 4.2 Callback Pattern
function writeCode(callback) { // do something... callback(); // ... } function introduceBugs() { // ...
- JavaScript Patterns 2.6 switch Pattern
Principle • Aligning each case with switch(an exception to the curly braces indentation rule). • Ind ...
- 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, ...
- 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 ...
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
随机推荐
- Oracle Error - "OCIEnvCreate failed with return code -1 but error message text was not available".
ISSUE: When trying to connect to an Oracle database you receive the following error: "OCIEnvCre ...
- python的metaclass
元类一般用于创建类.在执行类定义时,解释器必须要知道这个类的正确的元类.解释器会先寻找类属性__metaclass__,如果此属性存在,就将这个属性赋值给此类作为它的元类.如果此属性没有定义,它会向上 ...
- dapper 注意事项之GUID
今天把ef框架换成了dapper,数据库使用的是mysql. 主键使用GUID,mysql数据库中设置的为varchar(36). 使用dapper报错,不能将string转换为GUID,后来调试比对 ...
- 【C#进阶系列】16 数组
首先提一下,个人在项目中已经很少用到数组了,更多的时候使用List<>. 数组大小固定,如果只是用来存放数据,专门用来读取,更改当然方便.但是更多的时候我们需要进行增删改,这个时候用Lis ...
- GitHub上下载源代码的方法
GitHub上找到自己要下载的项目以后,有3种方法可以下载源代码. 第一种是复制该项目的地址,然后用其他软件下载: 第二种是安装了官方客户端,可以直接点击"Clone in Desktop& ...
- 2016 大连网赛---Weak Pair(dfs+树状数组)
题目链接 http://acm.split.hdu.edu.cn/showproblem.php?pid=5877 Problem Description You are given a rooted ...
- Maven编译jar出现:无法确定 T 的类型参数的异常的原因和处理方案
出错场景: 代码: public class JsonUtil { private static final Gson gson = new GsonBuilder().setDateFormat(& ...
- MyEclipse10 中的两种FreeMarker插件的安装与配置
第一个插件是: freemarker-ide MyEclipce10.0中安装FreeMarker插件,这绝对是最简单的方法 ...
- 常见.NET功能代码汇总
1,在Web上修改指定文件位置的Web.config 这里需要使用 WebConfigurationManager 类,但必须使用WebConfigurationFileMap类来指定文件位置,看代码 ...
- 我开发 wangEditor-mobile 的故事
wangEditor-mobile 是一款适用于手机.手指操作的富文本编辑器,wangEditor-mobile 官网 1. 写在前面 其实,我一开始并没有想做什么手机端操作的富文本编辑器. w ...