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) ...
随机推荐
- C#自定义特性实例
元数据,就是C#中封装的一些类,无法修改.类成员的特性被称为元数据中的注释. 1.什么是特性 (1)属性与特性的区别 属性(Property):属性是面向对象思想里所说的封装在类里面的数据字段, ...
- TextBox禁止复制粘贴和数字验证,小数验证,汉字验证
验证小数 #region 验证小数 /// <summary> /// 验证小数 /// </summary> /// <param name="sender& ...
- 【算法和数据结构】_12_小算法_abs_fabsf_fabsd_大端小端判断
最近学习要用到求绝对值函数,看了一下有很多种的abs函数,因此想自己实现这些代码. 下面是我进行测试的代码: #include <stdio.h> typedef unsigned int ...
- Ajax中传递Json格式的参数
$.ajax({ type: "post", url: baseUrl+"sys/login", dataType: "json", con ...
- IIS 7 托管管道模式 经典模式(Classic) 集成模式(Integrated) 分析与理解
IIS 7.0 支持两种管道模式:一种是IIS 7.0最新提供的集成管道模式,另一种是经典管道模式,经典管道模式是由先前版本的IIS提供的. 我们可以通过应用程序池设置管道模式,这项功能对IIS管理员 ...
- oracle RAC的VIP和scan
我们都知道Oracle RAC中每个节点都有一个虚拟IP,简称VIP,与公网IP在同一个网段. 没有VIP时,Oracle客户端是靠"TCP/IP协议栈超时"来判断服务器故障.而T ...
- 学习 Mobile App 网站制作的11个优秀案例
我喜欢收集美丽的,精心设计的移动应用程序网站.在我看来,为 App 提供一个美丽的网站显示了设计者和开发者对它的用户和产品的关心,除了开发应用程序,他们去加倍努力去促进应用和传播关于它的 App. 我 ...
- ExtJS numberfield textfield用法
textfield的用法示例 var formCmp = Ext.create("Ext.form.Panel", { title: "NumberField用法示例&q ...
- go语言 类型:基础类型和复合类型
Go 语言中包括以下内置基础类型:布尔型:bool整型:int int64 int32 int16 int8 uint8(byte) uint16 uint32 uint64 uint浮点型:floa ...
- 前端js文件合并三种方式
最近在思考前端js文件该如何合并,当然不包括不能合并文件,而是我们能合并的文件,想了想应该也只有三种方式. 三个方式如下: 1. 一个大文件,所有js合并成一个大文件,所有页面都引用它. 2. 各个页 ...