Starsing 发表于 2013-1-23 02:08:39

js代码发表测试

/** * @author Star */    if(typeof(kaho) == 'undefined')    var kaho = {};/** * @type {object} */kaho.util = { };kaho.util.Borwers = { };kaho.util.request = false;kaho.util.userId = "";kaho.util.clientId = "";kaho.util.pageUrl = "";kaho.util.serverUrl = "";kaho.util.siteUrl = "Blank";(function(){kaho.Event = { };kaho.Event.ieEventType = ["onclick"];kaho.Event.ffEventType = ["click"];/** * @type {array} */kaho.Event.callBackListener = [];kaho.Event.triggerListener = [];/** * call back function name , param is json string or null * @param {Object} callBack Function handle */kaho.Event.addCallBackListener = function(callBackFunction){if(typeof(callBackFunction) != 'function') {alert("need function handle !");return;}kaho.Event.callBackListener.push(callBackFunction);};/** ** @param {Object} triggerFunction */kaho.Event.addTriggerListener = function(triggerFunction){if(typeof(triggerFunction) != 'function') {alert("need function handle !");return;}kaho.Event.triggerListener.push(triggerFunction);};/** ** @param {String} callBackFunction */kaho.Event.deleteCallBackListenerUseName = function(callBackFunction){var len = kaho.Event.callBackListener.length;for(var i = 0 ; i < len ; i ++){var method = kaho.Event.callBackListener;if(method.getName() == callBackFunction.trim()){kaho.Event.callBackListener.removeIndex(i);return;}}};/** ** @param {Object} triggerFunction */kaho.Event.deleteTriggerListener = function(triggerFunction){      kaho.Event.triggerListener.removeElement(triggerFunction);};/** ** @param {Object} callBackFunction */kaho.Event.deleteCallBackListener = function(callBackFunction){kaho.Event.callBackListener.removeElement(callBackFunction);};/** * call back function name , param is json string * @param {String} callBackFunction * @return {Object} callBackFunction */kaho.Event.getCallBackListener = function(callBackFunction /* server call back functon */){var len = kaho.Event.callBackListener.length;for(var i = 0 ; i < len ; i ++){var method = kaho.Event.callBackListener;if(method.getName().toLowerCase() == callBackFunction.toLowerCase()){return method;}}return false;};/** * call back param null function * @param {String} callBackFunction */kaho.Event.callFunction = function(callBackFunction /*client js function name */){var method = kaho.Event.getCallBackListener(callBackFunction);if(method) method();return;};/** ** @param {String} callBackFunction * @param {Object} param */kaho.Event.callFunctionUseParam = function(callBackFunction , param){var method = kaho.Event.getCallBackListener(callBackFunction);if(method) method(param);return;};/** * @see kaho#Event.ieEventType and kaho#Event.ffEventType * @return {Number} */kaho.Event.eventCount = function(){var ieTypeCount = kaho.Event.ieEventType.length;var ffTypeCount = kaho.Event.ffEventType.length;return ieTypeCount <= ffTypeCount ? ieTypeCount : ffTypeCount;};/** **/kaho.Event.runOnConnect = function(){var length = kaho.Event.triggerListener.length;for(var i = 0 ; i < length ; i ++){var method = kaho.Event.triggerListener;if(typeof(method) != 'function') continue;method();}};})();kaho.util.isIE = true;kaho.util.Borwers.getEventInt = function(eventType /*String ,what ? ouy like */){var count = kaho.Event.eventCount();for(var i = 0 ; i < count ; i ++){if(kaho.Event.ieEventType == eventType || kaho.Event.ffEventType == eventType) return i;}return -1;};/** * when page unload run the method * @param {function} */kaho.util.onload = function(method /* function name*/){if(document.all){window.attachEvent("onload",method);}else{    window.addEventListener("load",method , false);}};/** ** @param {Object} method */kaho.util.loadComplete = function(method){               if (document.all) {document.onreadystatechange = function(){if (document.readyState == "complete") method();}}else document.addEventListener("DOMContentLoaded", method, false);};/** * when page load run the method * @param {js function name} */kaho.util.unload = function(method /* function name*/){if(kaho.util.isIE){            window.attachEvent("onunload",method);}else{   window.addEventListener("unload",method , false);}};    /**   *      * @param {String}      * @return dom object   */kaho.util.getId = function(elementId /*String*/){return document.getElementById(elementId);};/** * hidden the element at page * @param {String} */kaho.util.hidden = function(elementId /*String*/){kaho.util.getId(elementId).style.display = "none";};/** ** @param {array} elementList */kaho.util.hiddenElementList = function(elementList /* element array*/){if(elementList.constructor != window.Array) return;for(var i = 0 ; i < elementList.length ; i ++)kaho.util.hidden(elementList);};/** * show the element at page * @param {String} */kaho.util.show = function(elementId /*String*/){kaho.util.getId(elementId).style.display = "";};/** ** @param {Array} elementList */kaho.util.showElementList = function(elementList /* element array*/){if(elementList.constructor != window.Array) return;for(var i = 0 ; i < elementList.length ; i ++)kaho.util.show(elementList);};/** * why ??? * @deprecated test * @return {object} json */    kaho.util.batch1 = (function(){return {"json_channel": "","json_mark": "","json_meta": "","url": "","req": false,"body": ""}})();/** * 2009-05-06 17:04 delete var request in json batch* , need new action , default genaral Communications batch * @return {object} json */kaho.util.batch = (function(){return {"json_channel": "", // json_reconnect"json_mark": "","json_meta": "", // inner channel"json_browser" : "","data_from" : "","url": "","callback" : "","param" : false,"body": "" //{'data_from' : "" , 'data_to' : "" , 'data_body' :}}});/** * default connection batch for connecting server *not need init like 'new or ()', at complier time it run itself * @return {Object} json */kaho.util.connectBatch = (function(){return {"json_channel": "comet_tec", "json_mark": "","json_meta": "", "json_browser" : document.all,"data_from" : "","url": "","callback" : "","param" : false //has param or not//"body": ""//data from server ,it is function param json data}})();kaho.util.reConnectBatch = (function(){return {"json_channel": "json_reconnect", "json_mark": "","json_meta": "", "json_browser" : document.all,"data_from" : "","url": "","callback" : "","body": ""}});/** ** @param {String} serverTarget */kaho.util.setServerUrl = function(serverTarget){kaho.util.serverUrl += "/" + serverTarget;};/** **/kaho.util.reSetServerUrl = function(){kaho.util.serverUrl = kaho.util.siteUrl;};/** * bind method to object with event type * method must null param function' handle * @param {String } Event type , * @param {Object} (page dom id) or (page dom element) * @param {Object} */kaho.util.bind = function( eventType /*Event type String */, elementIdOrDom /*String or dom object*/ , handler /* js method*/){var element = typeof(elementIdOrDom) == "object" ? elementIdOrDom : kaho.util.getId(elementIdOrDom);var count = kaho.util.Borwers.getEventInt(eventType);if(count < 0) return ;if(document.all){element.attachEvent( kaho.Event.ieEventType, handler);}else{element.addEventListener( kaho.Event.ffEventType , handler , false);}};/** ** @param {Object}* @param {Object}* @param {Object} */kaho.util.removeBind = function( eventType /*Event type String */, elementIdOrDom /*String or dom object*/ , handler /* js method*/){var element = typeof(elementIdOrDom) == "object" ? elementIdOrDom : kaho.util.getId(elementIdOrDom);var count = kaho.util.Borwers.getEventInt(eventType);if(count < 0) return ;if(kaho.util.isIE){element.detachEvent( kaho.Event.ieEventType, handler);}else{         element.removeEventListener( kaho.Event.ffEventType , handler ,false);}};/** * type like [{ k : v },{ k : v}] json, * return [{ k : v }],[{ k : v }] * @param {Array} jsonArry * @return {Array} */kaho.util.jsonArryToArry = function(jsonArry /* jsonObjectArray*/){if(jsonArry == false) return false;var arry = [];var len = jsonArry.length;for(var i = 0 ; i < len ; i ++){arry.push(jsonArry);}return arry;};/** * type like { k : v }{ k : v} string , * return[{ k : v },{ k : v}] json * @param {String} serverJsonString * @return {Array} type like */kaho.util.jsonStringToArray = function(serverJsonString /* json array string type*/){    if(serverJsonString.trim().length <= 0) return [];      try {            return JSON.parse('[' + serverJsonString.trim().replaceAll('}{', '},{') + ']');      } catch (e) {         alert("Error message\n"+e.message);return [];      }return [];;};/** ** @param {String}*/kaho.util.serverStringToArray = function(serverJsonString /* json array string type*/){return kaho.util.jsonArryToArry(kaho.util.jsonArryToArry(serverJsonString));};/** * change string to js method and run it * @param {String} */kaho.util.toEval = function(strScript /* javscript stream*/){if(strScript == null || strScript.trim().length == 0) return;try{eval(strScript);}catch(e){alert("Exception : from kaho.util.toEval\n" + e.message);}};/** * write js string to page * @param {String}*/kaho.util.writeScript = function(strScript /* javascript stream*/){if(strScript == null || strScript.trim().length == 0) return;if(!strScript.startWithNoCase("<script type=\"text\/javascript\">"))strScript = "<script type=\"text\/javascript\">\t\n"+strScript;if(!strScript.endWithNoCase("<\/script>"))strScript = strScript + "\n<\/script>";document.write(strScript);};/** * something when page load */kaho.util.initInfo = function(){kaho.util.isIE = typeof(window.ActiveXObject) == "undefined" ? false : true;kaho.util.pageUrl = window.location;kaho.util.serverUrl = kaho.util.siteUrl =window.location.protocol + "//" + window.location.host;};    /**   * delete left and right spaces      * @return {String}   */    String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g, ""); };/** * delete left spaces * @return {String} */String.prototype.Ltrim = function(){return this.replace(/(^\s*)/g, ""); };/** * delete right spaces * @return {String} */String.prototype.Rtrim = function(){return this.replace(/(\s*$)/g, ""); };    /**   * test string is start with the string   * @param {String} startStr   * @return {Boolean}   */    String.prototype.startWith = function(startStr){if(startStr == null || startStr == "" || startStr.length == 0 || startStr.length > this.length)   return false;if(this.substr( 0 , startStr.length) == startStr)return true;elsereturn false;return true;};/** * test string is start with the string and no case * @param {String} startStr * @return {Boolean} */String.prototype.startWithNoCase = function(startStr){if(startStr == null || startStr == "" || startStr.length == 0 || startStr.length > this.length)   return false;if(this.substr( 0 , startStr.length).toLowerCase() == startStr.toLowerCase())return true;elsereturn false;return true;};    /**   * test string is end with the string   * @param {String} endWith   * @return {Boolean}   */String.prototype.endWith = function(endStr){if(endStr == null || endStr == "" || endStr.length == 0 || endStr.length > this.length)   return false;if(this.substring(this.length - endStr.length) == endStr)   return true;else    return false;return true;}; /**   * test string is start with the string and no case   * @param {String} endWith   * @return {Boolean}   */String.prototype.endWithNoCase = function(endStr){if(endStr == null || endStr == "" || endStr.length == 0 || endStr.length > this.length)   return false;if(this.substring(this.length - endStr.length).toLowerCase() == endStr.toLowerCase())   return true;else    return false;return true;};/** ** @param {String} from * @param {String} to */String.prototype.replaceAll = function(from , to){return this.replace(new RegExp(from,"gm"),to);};/** * return function'name * @return {String} */Function.prototype.getName = function(){var classStr = this.toString();var name = classStr.substring(classStr.indexOf('function') + 8 , classStr.indexOf('(')).trim();if(name.length <= 0) return false;return name;};/** * index use array subscript * @param {Number} index */Array.prototype.removeIndex = function(index /* array index */){if(typeof(index) != 'number' ||(index > this.length || index <= 0)) return this;return this.slice( 0 , index ).concat(this.slice(index + 1 , this.length));};/** * remove current element from array * @param {Object} element */Array.prototype.removeElement = function(element /* array element */){if(this.length <= 0) return;for(var i = 0 ; i < this.length ; i ++){if(this == element){this.removeIndex(i);                break;}}};/** * AJAX send message and get message method */(function(){/** * Reverse AJAX method ^_^.<br/> * core code I think **/kaho.reverseAjax = {sync : true,connectBatch : "",/** * send push messsage with normal request * @param {Object} \ (message bath) */send : function(batch /* message bacth*/){if(typeof(kaho.reverseAjax.connectBatch) =="string") kaho.reverseAjax.connectBatch = batch;batch.json_browser = kaho.util.isIE;batch.url = kaho.util.serverUrl;var request = kaho.ajax.xhr.initReq();            request.open("post", batch.url, kaho.ajax.xhr.sync);            if (request.overrideMimeType)               request.overrideMimeType('text/json; charset=utf-8');            request.setRequestHeader("cache-control", "no-cache");            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");            request.onreadystatechange = function(){                kaho.reverseAjax.processState(request);            };request.send("batch=" + JSON.stringify(batch));},/** * when readystate change run the method * @param {Object} request */processState : function(request /* current XMLHttpRequest*/){switch(request.readyState){case 0 : break;case 1 : break;case 2 : break;case 4 : {switch (request.status) {case 200:kaho.reverseAjax.processCometResponse(request);break;case 404:alert("Request Url is not found !");break;case 505:alert("Code : "+request.status + "\n" + request.statusText);break;default :alert("Code : "+request.status + "\n" + request.statusText);};break;}      default : kaho.reverseAjax.processCometResponse(request);//3}},/** ** @param {Object} current request */processCometResponse : function(request /* response text from server with push*/){if (request.readyState == 3 && kaho.util.isIE) return;var jsonArry = kaho.util.jsonStringToArray(request.responseText);if(jsonArry.constructor != window.Array){request.abort();alert("JSON Protocol is not init from server response!");return;}var tempArray = kaho.util.jsonArryToArry(jsonArry);if(tempArray.constructor != window.Array) return;kaho.reverseAjax.messageQueue = tempArray;if(kaho.util.isIE) kaho.reverseAjax.historyCount = 0;var splitInt = kaho.reverseAjax.messageQueue.length - kaho.reverseAjax.historyCount;if (splitInt <= 0) return;kaho.reverseAjax.currentMessage = kaho.reverseAjax.messageQueue.slice(-splitInt);kaho.reverseAjax.historyCount = tempArray.length;kaho.listener.fire(request, kaho.reverseAjax.currentMessage);},currentMessage : [],messageQueue : [],historyCount : 0,reConnect : function(){var batch = kaho.reverseAjax.connectBatch;batch.json_channel = "json_reconnect";kaho.reverseAjax.send(batch);},/** * @deprecated* @param {Object}*/_abort : function(request /* message batch*/){request.abort();}};   /**    * AJAX normal method   */kaho.ajax = {xhr : {sync : true,initReq : function(){var request = false;var ms = ['Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0','Msxml2.XMLHTTP','Microsoft.XMLHTTP'];if(window.XMLHttpRequest){return new XMLHttpRequest();}else if(window.ActiveXObject){for(var i = 0 ; i < ms.length ; i ++ ){try{request = new ActiveXObject(ms);return request;}catch(e){continue;}}}return false;},send : function(batch /* message batch*/){var request = kaho.ajax.xhr.initReq();batch.url = kaho.util.serverUrl;batch.json_browser = kaho.util.isIE;    request.open("post" , batch.url ,kaho.ajax.xhr.sync);if(request.overrideMimeType)   request.overrideMimeType('text/json; charset=utf-8');request.setRequestHeader("cache-control","no-cache");                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");request.onreadystatechange = function(){switch(request.readyState){       case 0 : break;       case 1 : break;       case 2 : break;       case 4 : {      switch (request.status) {   case 200:kaho.ajax.xhr.processState(request);break;   case 404:alert("Request Url is not found !");break;   case 505:alert("Code : "+request.status + "\n" + request.statusText);break;   default :alert("Code : "+request.status + "\n" + request.statusText);   };break;      }             default : break;//kaho.ajax.xhr.processState(request);      }};                request.send("batch=" + JSON.stringify(batch));},/** ** @param {Object} request */processState : function(request /* XMLHttpRequest */){if (request.readyState == 3 && kaho.util.isIE) return;var jsonArry = kaho.util.jsonStringToArray(request.responseText);if(jsonArry.constructor != window.Array){request.abort();alert("JSON Protocol is not init from server response!");return;}if(jsonArry.length <= 0) return;kaho.ajax.responseHistory = kaho.util.jsonArryToArry(jsonArry);if(kaho.ajax.responseHistory.length <= 0) return;kaho.channel.fire(request , kaho.ajax.responseHistory);},/** ** @param {Object} request */constructRequest : function(request /* XMLHttpRequest */){return request;},/** * cancle current request , above fireFox look like do not run * @param {Object} batch */            _abort: function(request /* message batch*/){                request.abort();            }},responseHistory : []};})();/** * process response from server */(function(){/** ** @param {Object} request */kaho.channel = function(request){this.request = request;};kaho.channel.prototype = {/** * A&Q channel responseprocess * @param {Object} message */fireEvent : function(message){    //alert("Back message from server\n"+JSON.stringify(message));//if(message.json_channel != 'message_ok')//return false;if(typeof(message.callback) != 'undefined'){//alert("callbakc json = "+JSON.stringify(message));if(typeof(message.param) != 'undefined')kaho.Event.callFunctionUseParam(message.callback , message.param);elsekaho.Event.callFunction(message.callback);}if(typeof(message.clientJs) != 'undefined'){kaho.util.writeScript(message.clientJs);}if(typeof(message.tempJs) != 'undefined'){kaho.util.toEval(message.tempJs);}//alert(JSON.stringify(message));            return true;}};/** * fire * @param {Object} request * @param {Object} messages */kaho.channel.fire = function(request /*current request */, messages /* JSON array from server*/){if(messages.constructor != window.Array) return;/** **/var currentChannel = new kaho.channel(request);for(var i = 0 ; i < messages.length ; i ++){var message = messages;if(!currentChannel.fireEvent(message)) break;}};/** * like the name , a class \u3067\u3059 * @param {Object} obj */    kaho.listener = function(request){      this.request = request;    };    kaho.listener.prototype = {/** ** @param {Object} message */      fireEvent: function(message){      //alert("json from server in comet\n"+JSON.stringify(message));            /**             *now deprecated             */if(typeof(message.json_meta) != 'undefined')            if (typeof(message.json_meta.disconnect) != 'undefined') {                if (message.json_meta.disconnect == 'ok') {                  this.request.abort();kaho.reverseAjax.connectBatch = "";return false;                }            }else if(typeof(message.json_meta.error) != 'undefined'){this.request.abort();      kaho.reverseAjax.reConnect();return false;}else if(typeof(message.json_meta.reconnect != 'undefined')){this.request.abort();      kaho.reverseAjax.reConnect();return false;}if(message.json_channel == 'json_disconnect'){ this.request.abort(); kaho.reverseAjax.connectBatch = ""; return false;}else if(message.json_channel == 'json_reconnect'){    alert("start reconnect!");this.request.abort();      kaho.reverseAjax.reConnect();return false;}else if(message.json_channel == 'connection_ok'){kaho.Event.runOnConnect();if(typeof(message.tempJs) != 'undefined')kaho.util.toEval(message.tempJs);return true;}//if(typeof(message.body) != 'undefined'){//kaho.util.toEval("test(" + message.body + ")");//}if(message.json_channel == 'message_ok'){if(typeof(message.tempJs) != 'undefined')kaho.util.toEval(message.tempJs);return true;}if(message.json_channel == 'json_general')if(typeof(message.callback) != 'undefined'){//alert("call back message\n"+JSON.stringify(message));if(typeof(message.param) != 'undefined')   kaho.Event.callFunctionUseParam(message.callback , message.param);else   kaho.Event.callFunction(message.callback);}if(typeof(message.clientJs) != 'undefined'){kaho.util.writeScript(message.clientJs);}if(typeof(message.tempJs) != 'undefined'){kaho.util.toEval(message.tempJs);}if(typeof(message.data_to) != 'undefined'){kaho.Event.getCallBackListener('getMessages')(message);}            return true;      }    };/** ** @param {Object} request * @param {Array} messages */kaho.listener.fire = function(request /*current request */, messages /* JSON array from server*/){if(messages.constructor != window.Array) return;var run = true;/** **/var cometListener = new kaho.listener(request);for(var i = 0 ; i < messages.length ; i ++){var message = messages;if(!(run = cometListener.fireEvent(message))) break;}if(run && kaho.util.isIE) kaho.reverseAjax.reConnect();};})();//(function(){alert("Hello world !");})();kaho.util.onload(kaho.util.initInfo);
页: [1]
查看完整版本: js代码发表测试