1. 程式人生 > >Js常用公共方法庫CommonHelper(持續更新)

Js常用公共方法庫CommonHelper(持續更新)

一直覺得應該有一個小小的js庫,看了js高階程式設計後,加上平時專案自己用的方法,整理編寫了一個自己的小助手

var LCH = {

        // remove value at array
        removeArrayItem: function (array, value) {
            var index = $.inArray(value, array);
            if (index > -1) {
                array.splice(index, 1);
            }
        },
        //value is exist in array
        isExistInArray: function (array, value) {
            var index = $.inArray(value, array);
            return index > -1 ? true : false;
        },
        // keyvaluedictionary
        keyValueDictionary: function () {
            var data = {};
            this.set = function (key, value) {
                data[key] = value;
            };
            this.unset = function (key) {
                delete data[key];
            };
            this.get = function (key) {
                return data[key] || null;
            }
        },
        // get parameters from Url
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            else {
                return undefined;
            }
        },
        //timestamp conversion(timestamp from .Net)
        getDataString: function (timestamp) {
            if (CommonHelper.IsNullOrWhiteSpace(timestamp)) {
                return "";
            }
            var timestampDate = timestamp.replace("/Date(", "").replace(")/", "");
            var tempDate = new Date(parseInt(timestampDate));
            Y = tempDate.getFullYear() + "-";
            M = (tempDate.getMonth() + 1 < 10 ? "0" + (tempDate.getMonth() + 1) : tempDate.getMonth() + 1) + "-";
            D = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
            h = tempDate.getHours() < 10 ? "0" + tempDate.getHours() : tempDate.getHours();
            m = tempDate.getMinutes() < 10 ? "0" + tempDate.getMinutes() : tempDate.getMinutes();
            s = tempDate.getSeconds() < 10 ? "00" : tempDate.getSeconds();
            return (Y + M + D + " " + h + ":" + m + ":" + s);
        },
        //  indicates whether a specified string is null, empty, or consists only of white-space
        IsNullOrWhiteSpace: function (stringValue) {
            var returnValue = false;
            if (typeof (stringValue) == "string") {
                stringValue = stringValue.replace(/(^\s*)|(\s*$)/g, "");
                if (stringValue == "") {
                    return true;
                }
                return false;
            }
            else {
                return true;
            }
        },
        //is exists  Prototype
        //return true  in  Prototype ,false not in Prototype
        hasPrototypeProperty: function (object, name) {
            //hasOwnProperty  when name in the prototype return true
            //in   if name exist return true
            return !object.hasOwnProperty(name) && (name in object);
        },
        //function currying
        curry: function (fn) {
            var args = Array.prototype.slice.call(arguments, 1);
            return function () {
                var innerArgs = Array.prototype.slice.call(arguments);
                var finalArgs = args.concat(innerArgs);
                return fn.apply(null, finalArgs);
            };
        },
        //function throttling ,frequent calls can use this
        throttle: function (method, context) {
            clearTimeout(method.tId);
            method.tId = setTimeout(function () {
                method.call(context);
            }, 100);
        },
        //IE9+、Firefox 4+和Chrome, But beyond that,use this
        bind: function (fn, context) {
            return function () {
                return fn.apply(context, arguments);
            }
        },
        ////eg.
        //// function handleMessage(event) {
        //// console.log("Message received: " + event.message);
        ////}
        //////建立一個新物件
        ////var target = new LCH.EventTarget();
        //////新增一個事件處理程式
        ////target.addHandler("message", handleMessage);
        //////觸發事件
        ////target.fire({ type: "message", message: "Hello world!" });
        //////刪除事件處理程式
        ////target.removeHandler("message", handleMessage);
        //////再次,應沒有處理程式
        ////target.fire({ type: "message", message: "Hello world!" });
        eventTarget: function () {
            this.handlers = {};
        }
    }
    LCH.EventUtil = {
        addHandler: function (element, type, handler) {
            if (element.addEventListener) {
                element.addEventListener(type, handler, false);
            } else if (element.attachEvent) {
                element.attachEvent("on" + type, handler);
            } else {
                element["on" + type] = handler;
            }
        },
        removeHandler: function (element, type, handler) {
            if (element.removeEventListener) {
                element.removeEventListener(type, handler, false);
            } else if (element.detachEvent) {
                element.detachEvent("on" + type, handler);
            } else {
                element["on" + type] = null;
            }
        }
    };
    LCH.CookieUtil = {
        get: function (name) {
            var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null;
            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(";", cookieStart);
                if (cookieEnd == -1) {
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart
                + cookieName.length, cookieEnd));
            }
            return cookieValue;
        },
        set: function (name, value, expires, path, domain, secure) {
            var cookieText = encodeURIComponent(name) + "=" +
            encodeURIComponent(value);
            if (expires instanceof Date) {
                cookieText += "; expires=" + expires.toGMTString();
            }
            if (path) {
                cookieText += "; path=" + path;
            }
            if (domain) {
                cookieText += "; domain=" + domain;
            }
            if (secure) {
                cookieText += "; secure";
            }
            document.cookie = cookieText;
        },
        unset: function (name, path, domain, secure) {
            this.set(name, "", new Date(0), path, domain, secure);
        }
    };
    LCH.eventTarget.prototype = {
        constructor: EventTarget,
        addHandler: function (type, handler) {
            if (typeof this.handlers[type] == "undefined") {
                this.handlers[type] = [];
            }
            this.handlers[type].push(handler);
        },
        fire: function (event) {
            if (!event.target) {
                event.target = this;
            }
            if (this.handlers[event.type] instanceof Array) {
                var handlers = this.handlers[event.type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    handlers[i](event);
                }
            }
        },
        removeHandler: function (type, handler) {
            if (this.handlers[type] instanceof Array) {
                var handlers = this.handlers[type];
                for (var i = 0, len = handlers.length; i < len; i++) {
                    if (handlers[i] === handler) {
                        break;
                    }
                }
                handlers.splice(i, 1);
            }
        }
    };

相關推薦

Js常用公共方法CommonHelper(持續更新)

一直覺得應該有一個小小的js庫,看了js高階程式設計後,加上平時專案自己用的方法,整理編寫了一個自己的小助手 var LCH = { // remove value at array removeArrayItem: function (ar

JS常用公共方法

erl .cn url pset ply con app rtrim coo /*******封裝一些常用的方法,如時間處理,數組去重等******/ /** * 去除字符串空格 * @param str 要處理的字符串 * @param type 1:所有

FIle類常用工具方法整理(持續更新

urn mef iou all filepath tabs ipa comm NPU 1.遞歸遍歷一個目錄,獲取所有文件名(也可以取到絕對路徑) public static void traverse(String filePath, List<String&g

JQ 常用的相關方法事件(持續更新中)

獲取元素 **$( ) ** $ 為必須, 括號中直接填寫css選擇器即可 $( ‘#book’ ) //獲取到id名為 book 這個元素 篩選 .find ( ) 搜尋所有與指定表示式匹配的元素。這個函式是找出正在處理的元素的後代元素的好方法。 find前面

python資料處理工具 pandas包常用方法總結(持續更新

======================== INTRODUCTION TO PANDAS  ======================== 圓括號是函式,方括號是索引 #Series data  can be numpy array,or a python dict

實現自己的js工具持續更新

(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 if (isAndroid) { return 'Android'; } else if (isiOS) { return 'iOS'

分享一個js常用方法

pty index def ie9 svg 輪播 hid window 常用 (function ($) { $.tools = function () { var _moduleTextPath = $.root + ‘templets/modu

linux 常用命令。。。持續更新

linux 常用命令1、Linux掛載Winodws共享文件夾 mount -t cifs -o username=name,password=123 //172.16.3.56/d /guaizai2、查看http的並發請求數及其TCP連接狀態:netstat -an | awk ‘/^tcp/{s[$

js常用方法

cond fonts 5.5 向上 簡單 適配 one 字符 overflow 1.時間格式化 a.需要熟悉Date對象的方法; b.使用 getFullYear(),getMonth(),getDate()等方法獲取年份,月份等時間數據,然後根據所需要的時間格式可以自行

Node.js常用express方法

apple req style form 手冊 規範 node ali 自動 Node.js 手冊查詢-Express 方法 1、send方法 send 方法向瀏覽器發送一個響應信息,並可以智能處理不同類型的數據 send方法在輸出響應時會自動進行一些設置,比

常用css屬性集(持續更新…)

wid 常用 process nowrap alt tex pro -s 51cto 禁止換行,超出部分顯示…:a. 代碼: .hide_word{ max-width: 100px; white-space:nowrap; overflow:hidden; text-ov

Python·Jupyter Notebook各種使用方法記錄·持續更新

question 使用 class ref not 使用方法 react article details Python·Jupyter Notebook各種使用方法記錄·持續更新 你為什麽使用 jupyterPython·Jupyter Notebook各種使用方

js常用API方法

top indexof() 字符串 gpo bject 包括 sea from 程序 String對象常用的API:API指應用程序編程接口,實際上就是一些提前預設好的方法。 charAt() 方法可返回指定位置的字符。 stringObject.charAt(index

js - 常用功能方法匯總(updating...)

output 方法 col tar purpose object 常用 匯總 pda 一、查值的類型(可用於拷貝) 1 /* 2 * @Author: guojufeng@ 3 * @Date: 2017-12-20 15:07:06

瀏覽器相容問題及解決方法彙總(持續更新......)

一、出現相容問題的原因:         瀏覽器種類很多,但是區別主要在瀏覽器核心的不同,所以各核心對網頁的解析差異,是導致瀏覽器相容問題出現的主要原因。關於瀏覽器核心(browser kernel),是瀏覽器最為核心

一些可能很常用的函式介紹(持續更新

一些次常用的函式介紹: replace replace(初始位置,結束位置,替換字串); find (母字串).find(子字串,起始位置) 如果沒有設定起始位置預設為從頭開始。 random_shuffle() random_shuffle(起始位置,結束位置)

React-Native開發中常用的第三方控制元件持續更新

筆者簡書:https://www.jianshu.com/u/8ba7c349861d, 歡迎大家關注 2018.8.23更新: 動態修改Android的softmodule: react-native-android-keyboard-adjust    

GMT常用小工具總結(持續更新

引言 正文 minmax函式 快速獲取檔案中每一列資料的最小最大值 例子: gmt minmax AODT_1064.txt gmt: Warning: module minmax is deprecated; use gmtinfo. AODT_1064.txt: N

Android常用工具類集合(持續更新

1.訊息通知管理類,適配Android8.0 https://blog.csdn.net/huangliniqng/article/details/83537119 2.Android撥打電話工具類:  https://blog.csdn.net/huangliniqng/

路由器終端常用linux命令彙總(持續更新

ls:顯示檔名與相關屬性 ls -al;ls -l;ls -a   第一列: d:表示目錄,dir。 -:表示檔案。 l:表示連結檔案,linkfile。 接下來的字元三個為一組,且均為rwx這3個字母的組合。r:read,w:write,x:execute。 第一組,檔案所有者