JS Sandbox Pattern
「Javascriptパターン」読みながら。
HTML
<div id="field"></div>
JavaScript
(function($){
$(function(){
/**
* @class Sandbox
*/
var Sandbox = function(){
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
var modules = (args[0] && typeof args[0] === 'string') ? args : args[0];
var i;
if(!(this instanceof Sandbox)){
return new Sandbox(modules, callback);
};
if(!modules || modules === '*'){
modules = [];
for(i in Sandbox.modules){
if(Sandbox.modules.hasOwnProperty(i)){
modules.push(i);
};
};
};
for(i = 0; i < modules.length; i++){
Sandbox.modules[modules[i]](this);
};
callback(this);
};
Sandbox.prototype = {
name : 'My Application',
version : '1.0',
getName : function(){
return this.name;
},
getVersion : function(){
return this.version;
}
};
Sandbox.modules = {};
Sandbox.modules.each = function(sandbox){
sandbox.each = $.each;
};
Sandbox.modules.xhr = function(sandbox){
sandbox.ajax = $.ajax;
};
Sandbox(['each', 'xhr'], function(sandbox){
sandbox.ajax({
url : 'http://search.twitter.com/search.json',
dataType : 'jsonp',
data : {
result_type : 'recent',
rpp : 10,
page : 1,
q : 'BarackObama'
}
}).then(function(res){
var field = document.getElementById('field');
var tweets = [];
sandbox.each(res.results, function(i, val){
tweets.push('<p>' + val.text + '</p>');
});
...