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) ...
随机推荐
- JAVA获取CLASSPATH路径
ClassLoader 提供了两个方法用于从装载的类路径中取得资源: public URL getResource (String name); public InputStream getResou ...
- 基于类型系统的面向对象编程语言Go
(整理自网络) 面向对象编程 Go语言的面向对象编程(OOP)非常简洁而优雅.说它简洁,在于它没有了OOP中很多概念,比如:继承.虚函数.构造函数和析构函数.隐藏的this指针等等.说它优雅,是它的面 ...
- 2015暑假多校联合---Mahjong tree(树上DP 、深搜)
题目链接 http://acm.split.hdu.edu.cn/showproblem.php?pid=5379 Problem Description Little sun is an artis ...
- Python Sqlite3以字典形式返回查询结果
sqlite3本身并没有像pymysql一样原生提供字典形式的游标. cursor = conn.cursor(pymysql.cursors.DictCursor) 但官方文档里已经有预留了相应的实 ...
- cnodejs社区论坛1--登陆
- Django messages框架
一.简介 在网页应用中,你经常需要在处理完表单或其它类型的用户输入后,显示一个通知消息(也叫做“flash message”)给用户 对于这个功能,Django 提供基于Cookie 和会话的消息,无 ...
- java集合-Iterator迭代
我们常常使用 JDK 提供的迭代接口进行 Java 集合的迭代. Iterator iterator = list.iterator(); while(iterator.hasNext()){ Str ...
- Quartz任务调度器
在使用jdk的timer时发现无法满足开发需求:即无法在指定的日期进行执行任务. 这便引入一个优秀的开源任务调度框架“quartz”. 这里加入的是quartz-1.8.6版本.Quart的官网: ...
- Windows 安装 GTK+ 图文说明
首先去官方下载: //官方网站 http://www.gtk.org/download/index.php //下载链接 http://win32builder.gnome.org/gtk+-bund ...
- [html5+java]文件异步读取及上传核心代码
html5+java 文件异步读取及上传关键代码段 功能: 1.多文件文件拖拽上传,file input 多文件选择 2.html5 File Api 异步FormData,blob上传,图片显示 3 ...