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) ...
随机推荐
- sql中 in , not in , exists , not exists效率分析
in和exists执行时,in是先执行子查询中的查询,然后再执行主查询.而exists查询它是先执行主查询,即外层表的查询,然后再执行子查询. exists 和 in 在执行时效率单从执行时间来说差不 ...
- Android实现系统重新启动
有些Android版本没有系统重启的功能,非常不方便.需要我们自己开发一个能够重新启动的应用. 首先定义布局文件: <?xml version="1.0" encoding= ...
- 迷信again
当在VirtualBox中尝试安装Debian 8.3.0 三次都失败后 - 每次卡在安装软件这一步,我决定不再迷信Debian软件包质量高这件事.
- 用于PHP的Gearman Worker管理工具GearmanManager
项目地址:https://github.com/brianlmoon/GearmanManager PHP环境要求 PHP 5.5.9 POSIX extension Process Control ...
- 解决SqlPlus前台程序出现中文乱码的问题
在使用sqlplus的过程中,常常会遇到某一台机器在访问oracle数据库时中文显示乱码的问题,实际上这是因为客户端字符集和服务器字符集不一致导致的.在实际使用中,服务器字符集,客户端字符集和操作系统 ...
- ThinkCMF-上传多个图片源码解读
关键函数: /** * 多图上传 * @param dialog_title 上传对话框标题 * @param container_selector 图片容器 * @param item_tpl_wr ...
- 2014年物联网Internet of Things应用简介
body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; } 物联网(Internet of Things,缩写I ...
- Nodejs与ES6系列2:Promise对象
2.promise对象 js单线程异步执行的特性,因此在代码中充斥着回调函数.随着回调函数的增加,代码的可读性会愈来愈差,因此引入promise对象是不错的一种选择,可以避免层层回调函数.在ECMA6 ...
- Bootstrap左侧下拉三级菜单
在线实例 效果一 效果二 效果三 使用方法 <script src="/api/jq/BootstrapCaidan/js/metismenu.js"></scr ...
- 基于 Node.js 平台的web开发框架-----express
express官网:---->传送门 express express框架有许多功能,比如路由配置,中间件,对于想配置服务器的前端来说,非常便捷 自从node发展之后,基于nodejs的开发框架 ...