Skip to content

Instantly share code, notes, and snippets.

@josue
Created April 30, 2011 23:50
Show Gist options
  • Save josue/950105 to your computer and use it in GitHub Desktop.
Save josue/950105 to your computer and use it in GitHub Desktop.
Common Javascript boot and usable methods for practical application development.
/* ===========================================================================
Copyright (c) 2011 - Josue Rodriguez <[email protected]>
Permission is hereby granted, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, and/or distribute copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. The Software may only be
used for non-commercial purposes, unless permission is granted by the copyright
author of the Software under an independent license. The Software can be used
and redistributed with third-party open-source software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================================================== */
ENV = window.ENV || {};
Views = window.Views || {};
UI = {};
debug = function(s){
window.console && console.log(s);
return false;
};
String.prototype.trim = function() { return this.toString().replace(/^\s+/,'').replace(/\s+$/,''); };
String.prototype.trimAll = function() { return this.toString().replace(/\s{2,}/g,' ').trim(); };
String.prototype.cleanAll = function() { return this.toString().replace(/[^\w\d\s\~\!\@\#\$\%\^\&\*\(\)\-\=\_\+\[\]\:\;\<\>\,\.\?\/\'\"\{\}]+/gi,''); };
String.prototype.cleanNum = function() { return this.cleanAll().replace(/[^\d\.\,\s]+/gi,''); };
String.prototype.cleanNumeric = function() { return this.cleanNum(); };
String.prototype.cleanAlpha = function() { return this.cleanAll().replace(/[^a-z\s\-\,\.\_]+/gi,''); };
String.prototype.cleanAlphaNum = function(){ return this.cleanAll().replace(/[^\w\d\s\-\,\.\_]+/gi,''); };
String.prototype.cleanAlphaOnly = function(){ return this.cleanAll().replace(/[^a-z\s\-]+/gi,''); };
String.prototype.cleanAlphaNumOnly = function(){ return this.cleanAll().replace(/[^a-z0-9\s\-]+/gi,''); };
String.prototype.cleanHTML = function() {
var s = this.cleanAll();
var x = '', h = { "@":"&#064;", '"':"&quot;", "<":"&#060;", ">":"&#062;", "&":"&amp;", "{":"&#123;", "}":"&#125;", "[":"&#091;", "]":"&#093;" };
for(var i=0; i<s.length; i++){ var a=s.charAt(i); x += (h[a] ? h[a] : a); }
return x;
};
String.prototype.lcase = function(){ return this.toString().toLowerCase(); };
String.prototype.ucase = function(){ return this.toString().toUpperCase(); };
String.prototype.toTitleCase = function() {
return this.toString().replace(/\w\S*/g, function(txt){
return txt.charAt(0).ucase() + txt.substr(1).lcase();
});
};
String.prototype.limit = function(t,c) {
var s = this.toString().replace(/<\/?\w+.*?>/gim, "");
return s.substr(0,t||50) + (c && s.length>=(t||50) ? c : '');
};
Number.prototype.limit = function(t) {
return parseInt(this.toString().substr(0,t||999));
};
Array.prototype.find = function(f) {
for(var i=0; i<this.length; ++i){
if(this[i]==f){ return i; }
}
return -1;
};
KEYS = { ENTER:13, RETURN:13, BACKSPACE:8, DELETE:46, ESCAPE:27, TAB:9, LEFT:37, UP:38, RIGHT:39, DOWN:40, COMMA:188, PERIOD:190 };
KEYS.simulate = function(type,key){
if(type && (KEYS[key] || typeof key=="number")) {
var key_id = KEYS[key] || key;
var e = jQuery.Event(type);
e.which = e.keyCode = e.charCode = key_id;
return e;
}
return null;
};
post_data = function(data,f){
var f = typeof f == "string" && f || null, post = {};
if(data instanceof Object) {
for(x in data) { post["data"+(f?"["+f+"]":'')+"["+x+"]"] = data[x]; }
}
return post;
};
to_params = function(serialize) {
var params = {};
for(var i in serialize) {
params[ serialize[i].name ] = serialize[i].value;
}
return params;
};
UI.View = function(view,opt) {
var data = Views[view] || view || null;
var opt = opt || {};
var remove_empties = opt.leave_empties || true;
var A = {};
A.render = function(vars) {
if(data==null) { return false; }
var new_data = data;
var params = vars || null;
if(typeof params == "object") {
if(opt.mergeData && typeof opt.mergeData === "object") {
$.extend(params,opt.mergeData);
}
for(x in params) {
if(typeof params[x] == "object") {
for(i in params[x]) {
var find = (opt.regexp) ? new RegExp("\{"+i+"\}",'gim') : "{"+i+"}";
new_data = new_data.replace(find, params[x][i]);
}
}
else {
var find = (opt.regexp) ? new RegExp("\{"+x+"\}",'gim') : "{"+x+"}";
new_data = new_data.replace(find, params[x]);
}
}
}
if(remove_empties) {
new_data = new_data.replace(/\{.*?\}/gi,'');
}
return new_data;
};
A.split = function() {
if(data==null) { return false; }
return data.replace(new RegExp("\{.*?\}",'gim'),"{_S_}").split("{_S_}");
};
return A;
};
UI.select = function(id,opt){
/* usage: UI.select("#ID",{opt}).data([{k:'',v:''},{k:'',v:''},...]).onClick(function(select){...}); */
var EL = $(id);
var opt = opt || {};
var el_trigger = opt.trigger || "click";
var def_tag = opt.def_tag || "a";
var parent = opt.parent || "ul";
var parent_id = opt.id || null;
var tag = opt.tag || "li";
var rel = opt.rel || "rel";
var found = (EL.length ? true : false);
if(!found) { throw(id + " not in DOM."); }
var selected = null;
var current_title = '';
var limit_chars = opt.limit_chars || 30;
var A = {};
A.title = function(title,t){
limit_chars = typeof t==="number" && t || limit_chars;
current_title = (typeof title==="string" && title||current_title).limit(limit_chars,'...');
$(def_tag,EL).attr('title',title).html(current_title);
return this;
};
A.data = function(d_opt,data,select){
var o = d_opt || {};
parent_id = o.id || parent_id;
var data = o.data || o || data;
var insertTo = o.insertTo || null;
var select = o.select || select || '';
var list = "";
var setTitle = o.title || null;
var tag_limit = o.tag_limit || 56;
var first_title = "";
var count = 1;
if(typeof parent_id === "string") {
$(parent, EL).attr('id',parent_id);
}
if(data instanceof Array === false) {
throw("(object) data must be in array"); return this;
// object data format: [ {k:123, v:'abc', attr:{....}, {.....} ] // attr is optional
}
for(var i in data) {
var info = data[i];
var attrs = [];
if(info.attr && typeof info.attr == "object") {
for(var ia in info.attr) {
attrs.push(ia+"=\""+info.attr[ia]+"\"");
}
}
attrs = attrs.join(" ").trim();
if(info.k && info.v) {
list += "<"+tag+" "+(select==info.k?"class='selected'":"")+" "+rel+"=\""+info.k+"\" "+attrs+">"+ info.v.limit(tag_limit,'...') +"</"+tag+">";
setTitle = (select==info.k ? info.v : setTitle);
if(count==1) {
first_title = info.v;
}
count++;
}
}
var b_cap = $(parent, EL).find('.b_cap');
if(insertTo && $(insertTo).length) {
$(insertTo).html(list);
}
else if(b_cap.length) {
$(parent+" "+tag+"["+rel+"]", EL).remove();
b_cap.before(list);
}
else {
$(parent+" "+tag+"["+rel+"]", EL).remove();
$(parent, EL).html(list);
}
A.title(setTitle || first_title);
return this;
};
A.select = function(t){
$(parent+" "+tag+"["+rel+"]", EL).removeClass("selected");
var set_selected = A.find_el(t);
if(set_selected && set_selected.length) {
set_selected.addClass("selected");
A.title(set_selected.text());
selected = set_selected;
}
return this;
};
A.find_el = function(t){
var found_it = $(parent+" "+tag+"["+rel+"='"+(t||'')+"']", EL);
if(found_it.length==0 && typeof t == "string") {
found_it = $(parent+" "+tag+t, EL);
}
else if(found_it.length==0 && typeof t == "number") {
found_it = $(parent+" "+tag, EL).eq(t);
}
return found_it && found_it.length && found_it || null;
};
A.get_el = function(i) {
return selected && selected.length && selected || null;
};
A.get_attr = function(a) {
return selected && selected.length && selected.attr(a) || null;
};
A.set_attr = function(a,v) {
selected && selected.length && selected.attr(a,v);
return this;
};
A.val = function(){
return A.get_attr(rel);
};
A.init = function(callback){
var callback = callback || opt.callback || false;
typeof callback == "function" && callback(A);
return this;
};
A.onClick = function(callback) {
opt.onClick = callback || false;
return this;
};
A.close = function(){
$(parent,EL).hide();
return this;
};
A.clicked = function(){
return typeof opt.onClick == "function" && opt.onClick(A) || false;
return this;
};
if(typeof parent_id === "string") {
$(parent, EL).attr('id',parent_id);
}
$(parent+" "+tag+"["+rel+"]", EL).live("click", function(e){
A.select($(this).attr(rel));
return typeof opt.onClick == "function" && opt.onClick(A) || false;
});
$(EL).live(el_trigger, function(){
$(parent,EL).show();
return false;
});
$(def_tag, EL).live(el_trigger, function(){
$(parent,EL).show();
return false;
});
return A;
};
UI.placeholder = function(id, opt){
var el = $(id);
var opt = opt || {};
var html = opt.html || opt.pic || "<img src='/img/ajax-loader.gif' border='0' />";
var A = {};
A.on = function(s){
$(".ui_placeholder",el).remove();
var div = $("<div>",{ 'class':'ui_placeholder', 'html': s || html });
el.html(div);
return this;
};
A.off = function(){
$(".ui_placeholder",el).remove();
return this;
};
return A;
};
UI.status = function(id) {
var el = $(id);
var _classes = "info success warning error validation";
var A = {};
A.clean = function(){
el.removeClass(_classes).empty();
return this;
};
A.show = function(c,s) {
A.clean();
el.addClass(c||"success").html(s);
return this;
};
A.success = function(s) {
A.show("success",s);
return this;
};
A.error = function(s) {
A.show("error",s);
return this;
};
A.info = function(s) {
A.show("info",s);
return this;
};
A.validation = function(s) {
A.show("validation",s);
return this;
};
return A;
};
// === jQuery useful events and other stuff....
$(function(){
// prevent hash anchors....
$("a[href=#]").live("click.safe",function(){ return false; });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment