seajs + jquery 底层封装

作者: 浅浅浅丿忧伤 | 来源:发表于2017-03-30 18:06 被阅读180次

    什么是seajs

    -seajs是一个加载器
    -遵循 CMD 规范模块化开发,依赖的自动加载、配置的简洁清晰。

    /*
     * @(#)init.js  2016年10月13日
     * homeanter
     * Copyright © 2001-2016, All rights reserved.
     * homeanter@163.com
     */
    /**
     * 数组
     */
    Array.prototype.forEach || (Array.prototype.forEach = function(e, t) {
        var r, n;
        if(null == this) throw new TypeError(" this is null or not defined");
        var i = Object(this),
            a = i.length >>> 0;
        if("function" != typeof e) throw new TypeError(e + " is not a function");
        for(arguments.length > 1 && (r = t), n = 0; n < a;) {
            var o;
            n in i && (o = i[n], e.call(r, o, n, i)), n++
        }
    }), 
    Array.prototype.map || (Array.prototype.map = function(e, t) {
        var r, n, i;
        if(null == this) throw new TypeError(" this is null or not defined");
        var a = Object(this),
            o = a.length >>> 0;
        if("[object Function]" != Object.prototype.toString.call(e)) throw new TypeError(e + " is not a function");
        for(t && (r = t), n = new Array(o), i = 0; i < o;) {
            var s, c;
            i in a && (s = a[i], c = e.call(r, s, i, a), n[i] = c), i++
        }
        return n
    });
    
    /**
     * date 
     * @param e
     */
    ! function(e) {
        "use strict";
        "function" != typeof Date.prototype.format && (Date.prototype.format = function(mask) {        
               
            var d = this;        
               
            var zeroize = function (value, length) {        
               
                if (!length) length = 2;        
               
                value = String(value);        
               
                for (var i = 0, zeros = ''; i < (length - value.length); i++) {        
               
                    zeros += '0';        
               
                }        
               
                return zeros + value;        
               
            };          
               
            return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function($0){
               
                switch($0) {        
               
                    case 'd':   return d.getDate();        
               
                    case 'dd':  return zeroize(d.getDate());        
               
                    case 'ddd': return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];        
               
                    case 'dddd':    return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()];        
               
                    case 'M':   return d.getMonth() + 1;        
               
                    case 'MM':  return zeroize(d.getMonth() + 1);        
               
                    case 'MMM': return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];        
               
                    case 'MMMM':    return ['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];        
               
                    case 'yy':  return String(d.getFullYear()).substr(2);        
               
                    case 'yyyy':    return d.getFullYear();        
               
                    case 'h':   return d.getHours() % 12 || 12;        
               
                    case 'hh':  return zeroize(d.getHours() % 12 || 12);        
               
                    case 'H':   return d.getHours();        
               
                    case 'HH':  return zeroize(d.getHours());        
               
                    case 'm':   return d.getMinutes();        
               
                    case 'mm':  return zeroize(d.getMinutes());        
               
                    case 's':   return d.getSeconds();        
               
                    case 'ss':  return zeroize(d.getSeconds());        
               
                    case 'l':   return zeroize(d.getMilliseconds(), 3);        
               
                    case 'L':   var m = d.getMilliseconds();        
               
                            if (m > 99) m = Math.round(m / 10);        
               
                            return zeroize(m);        
               
                    case 'tt':  return d.getHours() < 12 ? 'am' : 'pm';        
               
                    case 'TT':  return d.getHours() < 12 ? 'AM' : 'PM';        
               
                    case 'Z':   return d.toUTCString().match(/[A-Z]+$/);        
               
                    // Return quoted strings with the surrounding quotes removed        
               
                    default:    return $0.substr(1, $0.length - 2);        
               
                }        
               
            }); 
        });      
    }(window, void 0);
    
    (function($){
        $.extend($,{
            isNull:function(value){
                try {
                    if (value == "" || value == null || value == undefined) {
                        return true;
                    }
                    return new RegExp("^[ ]+$").test(value);
                } catch (e) {
                    return false;
                }
            },
            msg:{
                alert:function(msg,callback){
                    var index = layer.alert(msg,{
                        title:"系统提示",
                        closeBtn:0,
                        shadeClose: false
                    },function(){
                        layer.close(index);
                        typeof callback == "function" && callback();
                    });
                },
                confirm:function(msg,callback){
                    var index = layer.confirm(msg, {
                      btn: ['确定','取消'] //按钮
                    }, function(){
                        layer.close(index);
                        typeof callback == "function" && callback(true);
                    }, function(){
                        layer.close(index);
                        typeof callback == "function" && callback(false);
                    });
                },
            },
            blockUI:function(){
                $("body").data("loading",layer.load(1, {
                  shade: [0.5,'#3F3F3F'] //0.1透明度的白色背景
                }));
            },
            unblockUI:function(){
                layer.close($("body").data("loading"));
            },
            isIdcard:function(gets){
                /*
                该方法由网友提供;
                对身份证进行严格验证;
                */
            
                var Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 ];// 加权因子;
                var ValideCode = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ];// 身份证验证位值,10代表X;
            
                if (gets.length == 15) {   
                    return isValidityBrithBy15IdCard(gets);   
                }else if (gets.length == 18){   
                    var a_idCard = gets.split("");// 得到身份证数组   
                    if (isValidityBrithBy18IdCard(gets)&&isTrueValidateCodeBy18IdCard(a_idCard)) {   
                        return true;   
                    }   
                    return false;
                }
                return false;
                
                function isTrueValidateCodeBy18IdCard(a_idCard) {   
                    var sum = 0; // 声明加权求和变量   
                    if (a_idCard[17].toLowerCase() == 'x') {   
                        a_idCard[17] = 10;// 将最后位为x的验证码替换为10方便后续操作   
                    }   
                    for ( var i = 0; i < 17; i++) {   
                        sum += Wi[i] * a_idCard[i];// 加权求和   
                    }   
                    valCodePosition = sum % 11;// 得到验证码所位置   
                    if (a_idCard[17] == ValideCode[valCodePosition]) {   
                        return true;   
                    }
                    return false;   
                }
                function isValidityBrithBy18IdCard(idCard18){   
                    var year = idCard18.substring(6,10);   
                    var month = idCard18.substring(10,12);   
                    var day = idCard18.substring(12,14);   
                    var temp_date = new Date(year,parseFloat(month)-1,parseFloat(day));   
                    // 这里用getFullYear()获取年份,避免千年虫问题   
                    if(temp_date.getFullYear()!=parseFloat(year) || temp_date.getMonth()!=parseFloat(month)-1 || temp_date.getDate()!=parseFloat(day)){   
                        return false;   
                    }
                    return true;   
                }
                
                function isValidityBrithBy15IdCard(idCard15){   
                    var year =  idCard15.substring(6,8);   
                    var month = idCard15.substring(8,10);   
                    var day = idCard15.substring(10,12);
                    var temp_date = new Date(year,parseFloat(month)-1,parseFloat(day));   
                    // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getYear()方法   
                    if(temp_date.getYear()!=parseFloat(year) || temp_date.getMonth()!=parseFloat(month)-1 || temp_date.getDate()!=parseFloat(day)){   
                        return false;   
                    }
                    return true;
                }
            }
        });
    })(jQuery);
    
    ! function(e) {
        "use strict";
        
        function t(e) {
            for(var t = {}, n = t.toString, r = "Boolean Number String Function Array Date RegExp Object Error".split(" "), o = 0; o < r.length; o++) {
                var i = r[o];
                t["[object " + i + "]"] = i.toLowerCase()
            }
            return null === e ? e + "" : "object" == typeof e || "function" == typeof e ? t[n.call(e)] || "object" : typeof e
        }
    
        function n(e) {
            return "function" === t(e)
        }
        var r = e._ || (e._ = {}),
            o = !1,
            i = /xyz/.test(function() {}) ? /\bsuper\b/ : /.*/;
        r.Class = function() {}, 
        r.Class.extend = function a(e) {
            function t(e, t, n) {
                return function() {
                    return this._super = e[t], n.apply(this, arguments)
                }
            }
    
            function r() {
                !o && n(this.construct) && this.construct.apply(this, arguments)
            }
            var s = this.prototype;
            o = !0;
            var c = new this;
            o = !1;
            for(var u in e)
                if("statics" === u) {
                    var f = e[u];
                    for(var l in f) r[l] = f[l]
                } else {
                    n(s[u]) && n(e[u]) && i.test(e[u]) ? c[u] = t(s, u, e[u]) : c[u] = e[u];
                }
            return r.prototype = c, r.prototype.constructor = r, r.extend = a, r
        }
    }(window, void 0),
    function(e) {
        "use strict";
    
        function t(e) {
            var t = !1,
                n = e.split("?")[1];
            if(n)
                if(n = n.split("#")[0]) {
                    n = n.split("&");
                    for(var r = 0, o = n.length; r < o; r++) {
                        var i = n[r].split("=");
                        t = 2 === i.length && ("debug" === i[0] && "true" === i[1])
                    }
                } else t = !1;
            else t = !1;
            return t
        }
        for(var n, r = e._ || (e._ = {}), o = {}, i = ["assert", "cd", "clear", "count", "countReset", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "select", "table", "time", "timeEnd", "timeStamp", "timeline", "timelineEnd", "trace", "warn"], a = i.length, s = window.console = window.console || {}, c = function() {}; a--;) n = i[a], s[n] || (s[n] = c);
        var u = t(window.location.href);
        o = function(e) {
            this.debug = u
        }, 
        o.prototype = {
            log: function(e,o) {
                this.debug && s.log(e,o)
            },
            warn: function(e) {
                this.debug && s.warn(e)
            },
            error: function(e) {
                this.debug && s.error(e)
            },
            debug: function(e) {
                this.debug && s.debug(e)
            },
            info: function(e) {
                this.debug && s.debug(e)
            }
        }, 
        o.prototype.errorReport = function(e, t) {},
        r.console = new o
    }(window, void 0),
    function(e) {
        "use strict";
    
        function t(e, t, n) {
            var r;
            return r = t && t.hasOwnProperty("constructor") ? t.constructor : function() {
                e.apply(this, arguments)
            }, 
            $.extend(r, e),s.prototype = e.prototype,r.prototype = new s,t && $.extend(r.prototype, t), n && $.extend(r, n), r.prototype.constructor = r, r.__super__ = e.prototype, r
        }
    
        function n(e, n) {
            var r = t(this, e, n);
            return r.extend = this.extend, r
        }
    
        function r(e) {
            "undefined" != typeof e && e.callbacks ? this.callbacks = e.callbacks : this.callbacks = {}
        }
        var o = /\s+/,
            i = [].slice,
            a = e._ || (e._ = {}),
            s = function() {};
        r.extend = n,
        r.prototype = {
            on: function(e, t, n) {
                var r, i, a, s, c;
                if(!t) return this;
                for(e = e.split(o), r = this.callbacks; i = e.shift();) c = r[i], a = c ? c.tail : {}, a.next = s = {}, a.context = n, a.callback = t, r[i] = {
                    tail: s,
                    next: c ? c.next : a
                };
                return this
            },
            off: function(e, t, n) {
                var r, i, s, c, u, f;
                if(i = this.callbacks) {
                    if(!(e || t || n)) return delete this.callbacks, this;
                    for(e = e ? e.split(o) : a.keys(i); r = e.shift();)
                        if(s = i[r], delete i[r], s && (t || n))
                            for(c = s.tail;
                                (s = s.next) !== c;) u = s.callback, f = s.context, (t && u !== t || n && f !== n) && this.on(r, u, f);
                    return this
                }
            },
            trigger: function(e) {
                var t, n, r, a, s, c, u;
                if(!(r = this.callbacks)) return this;
                for(c = r.all, e = e.split(o), u = i.call(arguments, 1); t = e.shift();) {
                    if(n = r[t])
                        for(a = n.tail;
                            (n = n.next) !== a;) n.callback.apply(n.context || this, u);
                    if(n = c)
                        for(a = n.tail, s = [t].concat(u);
                            (n = n.next) !== a;) n.callback.apply(n.context || this, s)
                }
                return this
            }
        }, 
        a.Events = r,
        a.eventCenter = new r
    }(window, void 0),
    "object" != typeof JSON && (JSON = {}),
    function() {
        "use strict";
    
        function f(e) {
            return e < 10 ? "0" + e : e
        }
    
        function this_value() {
            return this.valueOf()
        }
    
        function quote(e) {
            return rx_escapable.lastIndex = 0, rx_escapable.test(e) ? '"' + e.replace(rx_escapable, function(e) {
                var t = meta[e];
                return "string" == typeof t ? t : "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
            }) + '"' : '"' + e + '"'
        }
    
        function str(e, t) {
            var n, r, o, i, a, s = gap,
                c = t[e];
            switch(c && "object" == typeof c && "function" == typeof c.toJSON && (c = c.toJSON(e)), "function" == typeof rep && (c = rep.call(t, e, c)), typeof c) {
                case "string":
                    return quote(c);
                case "number":
                    return isFinite(c) ? String(c) : "null";
                case "boolean":
                case "null":
                    return String(c);
                case "object":
                    if(!c) return "null";
                    if(gap += indent, a = [], "[object Array]" === Object.prototype.toString.apply(c)) {
                        for(i = c.length, n = 0; n < i; n += 1) a[n] = str(n, c) || "null";
                        return o = 0 === a.length ? "[]" : gap ? "[\n" + gap + a.join(",\n" + gap) + "\n" + s + "]" : "[" + a.join(",") + "]", gap = s, o
                    }
                    if(rep && "object" == typeof rep)
                        for(i = rep.length, n = 0; n < i; n += 1) "string" == typeof rep[n] && (r = rep[n], o = str(r, c), o && a.push(quote(r) + (gap ? ": " : ":") + o));
                    else
                        for(r in c) Object.prototype.hasOwnProperty.call(c, r) && (o = str(r, c), o && a.push(quote(r) + (gap ? ": " : ":") + o));
                    return o = 0 === a.length ? "{}" : gap ? "{\n" + gap + a.join(",\n" + gap) + "\n" + s + "}" : "{" + a.join(",") + "}", gap = s, o
            }
        }
        var rx_one = /^[\],:{}\s]*$/,
            rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
            rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
            rx_four = /(?:^|:|,)(?:\s*\[)+/g,
            rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        "function" != typeof Date.prototype.toJSON && (Date.prototype.toJSON = function() {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null
        }, Boolean.prototype.toJSON = this_value,Number.prototype.toJSON = this_value,String.prototype.toJSON = this_value);
        var gap, indent, meta, rep;
        "function" != typeof JSON.stringify && (meta = {
            "\b": "\\b",
            "\t": "\\t",
            "\n": "\\n",
            "\f": "\\f",
            "\r": "\\r",
            '"': '\\"',
            "\\": "\\\\"
        }, 
        JSON.stringify = function(e, t, n) {
            var r;
            if(gap = "", indent = "", "number" == typeof n)
                for(r = 0; r < n; r += 1) indent += " ";
            else "string" == typeof n && (indent = n);
            if(rep = t, t && "function" != typeof t && ("object" != typeof t || "number" != typeof t.length)) throw new Error("JSON.stringify");
            return str("", {
                "": e
            })
        }), 
        "function" != typeof JSON.parse && (JSON.parse = function(text, reviver) {
            function walk(e, t) {
                var n, r, o = e[t];
                if(o && "object" == typeof o)
                    for(n in o) Object.prototype.hasOwnProperty.call(o, n) && (r = walk(o, n), void 0 !== r ? o[n] = r : delete o[n]);
                return reviver.call(e, t, o)
            }
            var j;
            if(text = String(text), rx_dangerous.lastIndex = 0, rx_dangerous.test(text) && (text = text.replace(rx_dangerous, function(e) {
                    return "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
                })), rx_one.test(text.replace(rx_two, "@").replace(rx_three, "]").replace(rx_four, ""))) return j = eval("(" + text + ")"), "function" == typeof reviver ? walk({
                "": j
            }, "") : j;
            throw new SyntaxError("JSON.parse")
        })
    }(), 
    seajs.config({
        paths:{
            APP:scriptBasePath
        },
        alias:{
            "jquery.validate":"APP/jquery/jquery.validate.js",
            "jquery.validate.message":"APP/jquery/jquery.validator.messages_zh.js",
            "jquery.validate.method":"APP/jquery/jquery.validate.methods.js",
            "jquery.form":"APP/jquery/jquery.form.js",
            "jquery.tmpl":"APP/jquery/jquery.tmpl.js",
        }
    }),
    define("store", function() {
        "use strict";
    
        function e() {
            try {
                return o in r && r[o]
            } catch(e) {
                return !1
            }
        }
        var t, n = {},
            r = "undefined" != typeof window ? window : global,
            o = (r.document, "localStorage");
        n.disabled = !1, n.version = "1.3.20",
        n.set = function(e, t) {},
        n.get = function(e, t) {},
        n.has = function(e) {
            return void 0 !== n.get(e)
        }, 
        n.remove = function(e) {},
        n.clearByReg = function(e) {},
        n.clear = function() {},
        n.transact = function(e, t, r) {
            null == r && (r = t, t = null), null == t && (t = {});
            var o = n.get(e, t);
            r(o), n.set(e, o)
        }, 
        n.getAll = function() {
            var e = {};
            return n.forEach(function(t, n) {
                e[t] = n
            }), e
        }, 
        n.forEach = function() {}, 
        n.serialize = function(e) {
            return JSON.stringify(e)
        }, 
        n.deserialize = function(e) {
            if("string" == typeof e) try {
                return JSON.parse(e)
            } catch(t) {
                return e || void 0
            }
        }, 
        e() && (t = r[o], 
        n.set = function(e, r) {
            return void 0 === r ? n.remove(e) : (t.setItem(e, n.serialize(r)), r)
        }, 
        n.get = function(e, r) {
            var o = n.deserialize(t.getItem(e));
            return void 0 === o ? r : o
        }, 
        n.remove = function(e) {
            t.removeItem(e)
        }, 
        n.clearByReg = function(e) {
            var n = new RegExp(e);
            for(var r in t) n.test(r) && this.remove(r)
        }, 
        n.clear = function() {
            t.clear()
        }, 
        n.forEach = function(e) {
            for(var r = 0; r < t.length; r++) {
                var o = t.key(r);
                e(o, n.get(o))
            }
        });
        try {
            var i = "__storejs__";
            n.set(i, i), n.get(i) != i && (n.disabled = !0), n.remove(i)
        } catch(a) {
            n.disabled = !0
        }
        return n.enabled = !n.disabled, n
    }), 
    
    /**
     * ajax model
     * http://www.jquery123.com/category/ajax/low-level-interface/
     */
    define("ajax_setup", function(e) {
        var t = e("store");
        ! function() {
            function e(e, n) {
                var r = n.times,
                    o = n.backup,
                    i = e.timeout,
                    a = null;
                return function(s, c, u) {
                    function f(e) {
                        e && e.url === n.backup && (e.cache = !0, _.eventCenter.trigger(p.jsonpCallback + ":backup", n.backup)), p.data = p.__data || {}, $.extend(p, {
                            url: p.originalUrl,
                            forceStore: !1
                        }, e),
                        $.ajax(p).retry({
                            times: r - 1,
                            timeout: n.timeout,
                            statusCodes: n.statusCodes,
                            backup: o
                        }).pipe(h.resolve, h.reject)
                    }
    
                    function l() {
                        var e = t.get(p.storeKey);
                        e ? f({
                            forceStore: !0
                        }) : h.rejectWith(this, arguments)
                    }
                    var p = this,
                        h = new $.Deferred,
                        d = e.getResponseHeader("Retry-After");
                    return a && clearTimeout(a),
                    p.forceBackup && (r = 0),
                    r > 0 && (!e.statusCodes || $.inArray(s.status, e.statusCodes) > -1) ? (d && (i = isNaN(d) ? new Date(d).getTime() - $.now() : 3e3 * parseInt(d, 10), (isNaN(i) || i < 0) && (i = e.timeout)), void 0 !== i && r !== n.times ? a = setTimeout(f, i) : f()) : 0 === r ? "string" == typeof o && o.length > 0 ? f({
                        url: o
                    }) : l() : r === -1 ? l() : h.rejectWith(this, arguments), h
                }
            }
            $.ajaxPrefilter(function(n, r, o) {
                function i(e) {
                    var r = n.needStore,
                        o = n.storeKey,
                        i = n.storeCheck;
                    if(r = !!r && t.enabled) {
                        var a = t.get(o);
                        if(!a || !i(a)) {
                            if("string" == typeof e) try {
                                e = JSON.parse(e)
                            } catch(s) {
                                e = {}
                            }
                            t.set(o, e)
                        }
                    }
                }
                var a = $.Deferred();
                return o.done(function(e) {
                    var t = n.dataCheck;
                    $.isFunction(t) && !t(e) ? (r.url = r.backup, r.dataCheck = null, r.forceBackup = !0, a.rejectWith(r, arguments)) : (i(e), a.resolveWith(r, arguments))
                }),
                o.fail(a.reject), 
                o.retry = function(t) {
                    return t.timeout && (this.timeout = t.timeout), t.statusCodes && (this.statusCodes = t.statusCodes), this.pipe(null, e(this, t))
                }, 
                a.promise(o)
            }), 
            $.ajaxTransport("json", function(e) {
                var n = e.needStore,
                    r = e.storeKey,
                    o = e.storeCheck,
                    i = e.dataType,
                    a = e.forceStore;
                if(n = !!n && t.enabled) {
                    var s = t.get(r);
                    if(s && (o(s) || a)) 
                    return {
                        send: function(t, n) {
                            var r = {};
                            r[i] = s, n(200, "success", r, "")
                        },
                        abort: function() {
                            _.console.log("abort ajax transport for local cache")
                        }
                    }
                }
            })
        }()
    }),
    define("load_async", function(e) {
        return e("ajax_setup"),
        function(e) {
            e = $.extend({
                url: "",
                params: {},
                timeout: 3e3,
                times: 2,
                backup: null,
                needStore: !1,
                storeSign: null,
                cache: !1,
                dataCheck: null,
                dataType: "jsonp",
                type: "get",
                scriptCharset: "UTF-8",
                success:function(data){
                    
                }
            }, e);
            var t = function(e) {
                var t = e;
                return e;
            };
            return $.ajax({
                type: e.type,
                url: e.url,
                scriptCharset: e.scriptCharset,
                originalUrl: e.url,
                data: t(e.params),
                __data: t(e.params),
                dataType: e.dataType,
                jsonp: "callback",
                jsonpCallback: e.jsonpCallback,
                cache: e.cache,
                timeout: e.timeout,
                dataCheck: e.dataCheck,
                storeKey: e.storeKey || e.url,
                needStore: e.needStore,
                storeCheck: function(t) {
                    return !!t && t.version && t.version === e.storeSign
                },
                success:e.success
            }).retry({//重试
                timeout: e.timeout,
                times: e.times,
                backup: e.backup
            }).then(function(t) {
                if(t && (t.__uri = e.url)) {
                    var n = e.jsonpCallback + ":end";
                    _.eventCenter.trigger(n, t)
                }
            },function(t){
                _.console.log(e.url),_.console.log("请求接口和兜底都失败了")
            });
        }
    }),
    define("async_submit",["jquery.form"],function(e){
        return ("jquery.form"),
        function(e){
            e = $.extend({
                container:null,
                url:"",
                type:"post",
                data:null,
                success:null
            },e);
            return $(e.container).ajaxSubmit({
                url:e.url,
                type:e.type,
                data:e.data,
                success:e.success
            });
        };
    }),
    define("validate",["jquery.validate","jquery.validate.message","jquery.validate.method","jquery.form"],function(e){
        return (e("jquery.validate"),e("jquery.validate.message"),e("jquery.validate.method"),e("jquery.form")),
        function (e){
            e = $.extend({
                errorElement:"label",
                errorPlacement: function(error, element) {
                    error.insertAfter(element);
                },
                submitHandler:function(form) {
                    $(form).ajaxSubmit({
                        dataType:"json",
                        success:function(resp){
                            if(resp.statusCode==200){
                                window.location.href=contextPath + resp.forwardUrl;
                            }else{
                                $.alert(resp.message);
                            }
                        }
                    });
                },
                showErrors:null
            },e);
            var a = $(e.container).validate({
                errorElement:e.errorElement,
                errorPlacement:e.errorPlacement,
                submitHandler:e.submitHandler,
                onfocusout:false,
                ignore:true,
                showErrors:e.showErrors
            });
            return a;
        }
        
    }),
    define("open_new",function(e){
        return function(e){
            var features="width="+window.screen.availWidth+",height="+(window.screen.availHeight)+",top=0,left=0,toolbar=no,menubar=no,modal=yes,scrollbars=yes, resizable=yes,location=no, status=no";
            window.open(e.url,"",features);
        }
    }),
    define("datepicker",function(e){
        return function (e){
            if(typeof e == "object"){
                e = $.extend({
                    readOnly:false,
                    maxDate: 0,
                    dateFormat: 'yy-mm-dd'
                },e);
            }
            return $(e.container).datepicker(e);
        };
    }),
    /*工具类*/
    define("util",function(require, exports, module) {
        return {
            val:function(obj,val){
                var element = $(obj),
                    type;
                if(element instanceof jQuery){ 
                    if(element.length>1){
                        type = element[0].type;
                    }else{
                        type = element.type;
                    }
                    if(val){
                        if ( type === "radio") {
                            element.removeAttr("checked").filter("[value='"+val+"']").prop("checked",true);
                        }else if(type === "select"){
                            element.children("option").removeProp("selected").filter("[value='"+val+"']").prop("selected",true);
                        }else if(type === "checkbox"){
                            element.removeAttr("checked").filter("[value='"+val+"']").prop("checked",true);
                        }else{
                            element.val(val);
                        }
                        element.trigger("change")
                        return element;
                    }else{
                        if ( type === "radio") {
                            return $(element).filter(":checked").val();
                        }else if(type === "select"){
                            return $(element).filter(":selected").val();
                        }else if( type === "checkbox" ){
                            if(element.length>1){
                                var o = [];
                                $(element).filter(":checked").each(function(){
                                    o.push(element.val());
                                });
                                return o;
                            }else{
                                return element.val();
                            }
                        }else{
                            return element.val();
                        }
                    }
                }
            },
            text:function(obj,text){
                var element = $(obj);
                if(element instanceof jQuery){ 
                    if(text){
                        element.text(text);
                        return element;
                    }else{
                        return element.text();
                    }
                }
            },
            elFormat:function(source,params){
                if ( params === undefined ) {
                    return source;
                }
                if ( arguments.length > 2 && params.constructor !== Array  ) {
                    params = $.makeArray( arguments ).slice( 1 );
                }
                if ( params.constructor !== Array ) {
                    params = [ params ];
                }
                $.each( params, function( i, n ) {
                    source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {
                        return n;
                    });
                });
                return $(source);
            },
            checked:function(el,val){
                if(typeof val != "undefined"){
                    $(el).each(function(i,e){
                        var type = e.type;
                        if(type==="checkbox" || type === "radio"){
                            val === !!val && $(e).prop("checked",val);
                            $(e).trigger("change")
                        }
                    });
                    return $(el);
                }else{
                    return $(el).prop("checked")?true:false;
                }
            },
            disabled:function(el,val){
                if(typeof val != "undefined"){
                    $(el).each(function(i,e){
                        val === !!val && $(e).prop("disabled",val);
                    });
                    return $(el);
                }else{
                    return $(el).prop("disabled")?true:false;
                }
            },
            readonly:function(el,val){
                val === !!val && $(el).prop("readonly",val);
                return $(el);
            },
            options:function(el,data,flag){
                require("jquery.tmpl");
                var name = el.attr("id") || new Date().getTime();
                $.template(name,
                    "<option value='${value}' " +
                        "{{if checked}}checked='checked'{{/if}} " +
                        "{{if ext}} " +
                            "{{each ext}} {{= $value.key}}='{{= $value.value}}' {{/each}} " +
                        "{{/if}}" +
                    ">${text}</option>");
                if(flag){
                    el.html("");
                }
                $.tmpl(name,data).appendTo(el);
                $(el).trigger("change");
            },
            formToObject:function(container){
                var that = this;
                var element = $(container),
                    o = {};
                if(element instanceof jQuery){
                    var data = [];
                    element.each(function(i,obj){
                        if(obj.name){
                            data.push({name:obj.name, value:obj.value});
                        }
                    });
                    return that.arrayToObject(data);
                }
            },
            arrayToObject:function(array){
                var that = this,
                    o = {};
                typeof array === "object" && array.forEach(function(obj){
                    if(obj.name){
                        if (o[obj.name] !== undefined) {
                            if (!o[obj.name].push) {
                                o[obj.name] = [o[obj.name]];
                            }
                            o[obj.name].push(obj.value);
                        } else {
                            o[obj.name] = obj.value;
                        }
                    }
                });
                return o;
            }
        }
    }),
    define("tmpl",function(require){
        var ajax = require("load_async");
        return require("jquery.tmpl"),
        function(c){
            c = $.extend({
                name: null,
                url:null,
                data:{},
                callback: null
            }, c || {});
            ajax({
                url:c.url,
                dataType:"text",
                dataCheck:function(d){
                    if(!d) return !1;
                    $.template( c.name, d );
                    var obj = $.tmpl(c.name,c.data);
                    return $.isFunction(c.callback) && c.callback(obj),!0;
                }
            });
        }
    });
    

    相关文章

      网友评论

      本文标题:seajs + jquery 底层封装

      本文链接:https://www.haomeiwen.com/subject/jiypottx.html