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);
            }
        }
    };



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值