Skip to content

Instantly share code, notes, and snippets.

@marsen
Last active August 29, 2015 14:06
Show Gist options
  • Save marsen/b4c08488af62a945e7d9 to your computer and use it in GitHub Desktop.
Save marsen/b4c08488af62a945e7d9 to your computer and use it in GitHub Desktop.
Marsen Sandbox
//學習沙盒模式(Sandbox pattern)的範例
//順便整合一些之前常用的code,ex: 取亂數、取cookie等…
Marsen.modules = {} ;
Marsen.modules.web = function(box){
box.getQueryValue = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};//query string 取值
box.urlParser = function(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}//解析url
box.getCookie = function(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}//取得cookie
box.setCookie = function(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
};//設定cookie
Marsen.modules.common = function(box){
box.showObjectInfo = function (Obj){
for (var k in Obj) {
if (Obj.hasOwnProperty(k)) {
console.log("Obj." + k + ":" + Obj[k]);
}
}
};//顯示Object的資訊
box.tickToDate = function (t) {
var result = new Date(t).toString();
return result;
} //將tick轉成當地時間
box.random = function(Min,Max){
if(Max > Min){
//return Math.floor(Math.random() * (Max - Min + 1)) + Min;
return ~~(Max * Math.random())+Min;
}else{
console.log("function RandomNum exception");
}
};//產生一隨機數字
box.randomGuid = function(Min,Max){
return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};//產生一隨機GUID
box.randomDate = function(from,to) {
if (!from) {
from = new Date(1900, 0, 1).getTime();
} else {
from = from.getTime();
}
if (!to) {
to = new Date(2100, 0, 1).getTime();
} else {
to = to.getTime();
}
return new Date(from + Math.random() * (to - from));
};//產生一隨機日期
box.compile = function (template, data) {
return template.replace(/\{\s?([\w\s\.]*)\s?\}/g, function (str, key) {
key = $.trim(key);
var v = data[key];
return (typeof v !== 'undefined' && v !== null) ? v : '';
});//將template中所有的 {***} 變數 取代成 data[***]
}
};
Marsen.modules.event = function(box){
box.stopEventBubble = function(e) {
if (e && e.stopPropagation) {
e.stopPropagation();
}
else {//why always IE
window.event.cancelBubble = true;
}};//阻止事件冒泡
};
function Marsen() {
var args = Array.prototype.slice.call(arguments),
callback = args.pop(),
modules = (args[0] && (typeof args[0] === "string" && args[0] !== "*")) ? args : args[0],
i ;
//確保此函式是以建構式方式呼叫
if(!(this instanceof Marsen)) {
return new Marsen(modules,callback);
}
//自訂屬性
this.a =1;
this.b =2;
if(!modules || modules === '*' ){
modules = [];
for(i in Marsen.modules){
modules.push(i);
}
}
//初始化模組
for(i = 0;i < modules.length;i+=1){
Marsen.modules[modules[i]](this);
}
//執行callback
callback(this);
}
Marsen.prototype = {
name:"Marsen SandBox",
verson: "1.0",
getName: function(){
return this.name;
},
};
Marsen('*', function (box) {
//here is the sandbox inside
console.log(box);
});
@marsen
Copy link
Author

marsen commented Sep 24, 2014

可用在web開發

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment