util.js 13.7 KB
var $ = require('jquery');
var util = {
    __ajax: function(options, callback, notip) {
        if (typeof options.data == "string") {
            util.__tip(options.data, "warning");
            return false;
        } else {
            if(options.url.indexOf('?')==-1){
                options.url+="?";
            }
            options.url+="_datetime_="+Date.now();
            $.ajax({
                type: options.type || 'POST',
                url: options.url,
                async: options.async,
                dataType: 'json',
                data: options.data || {},
                success: function(result) {
                    res = result.data;
                    if(res){
                        if (("" + res.code) === "200") {
                            notip ? (callback && callback.bind(this, res)()) : util.__tip(res.message, "success", callback && callback.bind(this, res)());
                            return true;
                        } else {
                            (!notip) && util.__tip(res.message, "danger");
                            return false;
                        }
                    }else{
                        util.__tip(result.message, "danger");
                    }
                },
                error: function(err) {
                    if(err.status==200){
                       // location.href="/login";   
                    }
                    console.log("ajax.ERROR", err);
                    return false;
                }
            });
        }
    },
    __ajax2: function(options, callback, callback2) {
        if (typeof options.data == "string") {
            util.__tip(options.data, "warning");
        } else {
            if(options.url.indexOf('?')==-1){
                options.url+="?";
            }
            options.url+="_datetime_="+Date.now();
            $.ajax({
                type: 'POST',
                url: options.url,
                async: options.async,
                dataType: 'json',
                data: options.data || {},
                success: function(res) {
                    res = res.data;
                    if (res.code != 200) {
                        util.__tip(res.message, "warning");
                        return false;
                    } else {
                        return callback && callback.bind(this, res)();
                    }
                },
                error:function(res){
                    callback2 && callback2.bind(this, res)();
                    return false;
                }
            });
        }
    },
    __tip: function(message, callback) {
        //danger
        var options = {};
        options.class_name = "growl-danger";
        options.title = arguments[0];
        if (arguments.length > 1) {
            if (typeof(arguments[1]) === "string") {
                options.class_name = "growl-" + arguments[1];
            } else {
                options.class_name = "growl-success";
            }
            var lastargs = Array.prototype.slice.call(arguments, arguments.length - 1);
            lastargs = lastargs[0];
            if (typeof lastargs === "function") {
                options.after_open = setTimeout(function() {
                    lastargs && lastargs();
                }, 3000);
            }
        }
        options.sticky = false;
        options.time = 10000;

        $.gritter.add(options);
    },
    __template: function() {
        var args = arguments,
            result;
        if (args.length > 0) {
            if (typeof args[0] === "string") {
                result = args[0];
                if (args.length == 2 && typeof args[1] == "object") {
                    for (var key in args[1]) {
                        if (args[1][key] != undefined) {
                            var regkey = ((+key) == (+key)) ? "[" + key + "]" : key;
                            var reg = new RegExp("({" + regkey + "})", "g");
                            result = result.replace(reg, args[1][key]);
                        }
                    }
                }
                var reg = new RegExp("({.*})", "g");
                result = result.replace(reg, '');
            }
        }
        return result;
    },
    __template2: function(str, source) {

        function __layout(str){
            return str.replace(/\[\[\s*layout\s*([^\]]*)\]\]/mg,function($0,$1){
                return __layout(document.getElementById($1).innerHTML);
            });
        }
        str=__layout(str);
        

        var source=$.extend(true,{},source);
        // console.log(str);
        var script = [];
        script.push('var each=function(obj,fn){');
        script.push('            var that=this;');
        script.push('            if({}.toString.call(obj)=="[object Array]"){');
        script.push('                for(var i=0;i<obj.length;i++){');
        script.push('                    fn.call(i,i,obj[i]);');
        script.push('                }');
        script.push('                return;');
        script.push('            }');
        script.push('            if(typeof obj=="function"||typeof obj=="object"&&!!obj){');
        script.push('                for(var i in obj){');
        script.push('                    fn.call(i,i,obj[i]);');
        script.push('               }');
        script.push('               return;');
        script.push('            }');
        script.push('};');

        var formstr = function(code) {
            return "'" + code
                .replace(/('|\\)/g, '\\$1')
                .replace(/\r/g, '\\r')
                .replace(/\n/g, '\\n') + "'";
        }
        var formJs = function(code) {
                var trim = code.replace(/^\s+|\s+$/, '');
                //each goodsSizeList as item __index
                if (/^each/.test(trim)) {
                    return trim.replace(/^each\b([\w\W]+)\bas\b([\w\W]+)\b([\w\W]+)/, function($0, $1, $2, $3) {
                        return 'each\( ' + $1 + ',function(' + $3 + ',' + $2 + '){';
                    });
                } else if (/^\/each/.test(trim)) {
                    return trim.replace(/^\/each/, '});')
                } else if (/^if/.test(trim)) {
                    return trim.replace(/^if(.+)/, function($0, $1) {
                        return 'if(' + $1 + '){';
                    });
                } else if (/^\/if/.test(trim)) {
                    return trim.replace(/^\/if/, '};')
                } else if (/^else$/.test(trim)) {
                    return trim.replace(/else/, '}else{');
                } else if (/^else if/.test(trim)) {
                    return trim.replace(/^else if(.+)/, function($0, $1) {
                        return '}else if(' + $1 + '){';
                    });
                }else if(/^console\.[^\(]+\([^\)*]\)$/.test(trim)){
                    return trim+";";
                }else if(/^JSON\.[^\(]+\([^\)*]\)$/.test(trim)){
                    return trim+";";
                }
                // else if(/^layout\s+/.test(trim)){
                //     // var items=/^layout\s+(\w*)/.exec(trim);
                //     var items=trim.split(/\s+/g);
                //     items[2]=source[items[2]]||source;
                //     return "result.push('"+util.__template2(document.getElementById(items[1]).innerHTML,items[2]).replace(/\n/g,'')+ "')";
                // }
                else {
                    return "result.push(" + code + ")";
                }
            }
            // var PARAMS={};
        var OBJECT = /\.\w+|'.*'|".*"/g;
        var KEYWORDS = 'for,if,else,each,as,console,layout,JSON';
        var SPECHAR = /\W/g;
        var NUMBER = /^\d[^,]*|,\d[^,]*/g;
        
        var SPLIT2_RE = /^$|,+/;
        var REGEXKEYWORDS = new RegExp("\\b" + [KEYWORDS.replace(/,/g, '\\b|\\b')].join('|'), 'g');
        var getVar = function(code) {
            var strArr = code.replace(OBJECT, '')
                .replace(SPECHAR, ',')
                .replace(REGEXKEYWORDS, '')
                .replace(NUMBER, '')
                .split(SPLIT2_RE);
            for (var key in strArr) {
                if (strArr[key] && !source.hasOwnProperty(strArr[key])) {
                    source[strArr[key]] = "";
                }
            }
        }

        var code = [],
            params = {};
        var arr = str.split(/\[\[|\]\]/).map(function(item, index) {
            if (index % 2) {
                return {
                    value: item,
                    regex: true
                };
            } else {
                return {
                    value: item,
                    regex: false
                };
            }
        });

        arr.forEach(function(item, index) {
            if (item.regex) {
                getVar(item.value);
                code.push(formJs(item.value));
            } else {
                code.push("result.push(" + formstr(item.value) + ");");
            }
        });
        // var header="var result=[],";
        // header+=Object.keys(source).join(',')+";"

        var keys = [];
        for (var key in source) {
            if (typeof source[key] == "boolean") {
                keys.push(key + "=" + source[key]);
            } else {
                keys.push(key + "=" + JSON.stringify(source[key]));
            }
        }
        var params1=keys.join(',').length?","+keys.join(','):"";
        var header = "var result=[]" + params1 + ";";



        var result = header + code.join('\n') + "return result.join('');";

        var fn = new Function(script.join('') + result);
        return fn.call(source);
    },
    __input: function(id) {
        return !!~$.trim($('#' + id).val()) ? $('#' + id).val() : ""
    },
    __dateFormat: function(data, format) {
        if (!isNaN(data)) {
            var date = {
                "M+": data.getMonth() + 1,
                "d+": data.getDate(),
                "h+": data.getHours(),
                "m+": data.getMinutes(),
                "s+": data.getSeconds(),
                "q+": Math.floor((data.getMonth() + 3) / 3),
                "S+": data.getMilliseconds()
            };
            if (/(y+)/i.test(format)) {
                format = format.replace(RegExp.$1, (data.getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            for (var k in date) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
                }
            }

            return format;
        } else {
            return "";
        }

    },

    /**
     * 比较两个时间戳
     *
     */
    __compareDate:function(ts1, ts2) {
        return (ts1 < ts2);
    },

    __filterNull: function(obj, prop) {
        // 判断item里面 instr属性是不是为空
        if (obj[prop]) {
            return obj[prop];
        } else {
            return "";
        }
    },

    // 判断是否是有效的json字串
    __isJsonString: function (str) {
        try {
            var a=JSON.parse(str);
            if(typeof a=="object"){
                return true;
            }else{
                return false;
            }
        } catch (e) {
            return false;
        }

        return true;
    },
    __disButton:function(){
        var $this=this;
        $this.attr("disabled","disabled");
        setTimeout(function(){
            $this.removeAttr("disabled");
        },3000);
    },
    __joinImg:function(bucket,url) {
        var urlArr = url.split('/');
        var domain = 'static.yhbimg.com'+"/"+bucket;
        var num = urlArr[urlArr.length-1].substr(1,1);
        var url = domain + url;
        if(num == 1) {
            return 'http://img11.' + url; 
        } else {
            return 'http://img12.'+ url;
        }
    },
    __buildobj:function(str,symble,obj,fn){
        var arr = str.split(symble);
        var name = arr.shift();
        obj = obj || {};
        if(arr.length){
            if(/^\d+$/.test(name)){
                var objArr=$.extend(true,{},obj);
                if(!$.isArray(obj)){
                    obj=[];
                }
                obj[name] = objArr[name] || {};
            }else{
                obj[name] = obj[name] || {};
            }
            obj[name]=util.__buildobj(arr.join(symble),symble,obj[name],fn);
        }else{
            if(typeof fn == 'function'){
                if(/^\d+$/.test(name)){
                    obj=[];
                }
                fn(obj,name);
            }
        }
        return obj;
    },
    __ArrayToObj:function(data){
        var result={};
        if($.isArray(data)){
            data.forEach(function(item,index){
                result[index]=util.__ArrayToObj(item);
            });
        }else if(typeof data=="string"||typeof data=="number"||typeof data=="boolean"){
            result=data;
        } 
        else{
            for(var i in data){
                if(data.hasOwnProperty(i)){
                    result[i]=util.__ArrayToObj(data[i])
                }
            }
        }
        return result;
    },
    __ObjToArray:function(data){
        var result={};
        if([].toString.call(data)=="[object Object]"){
            for(var name in data){
                if(data.hasOwnProperty(name)&&/^\d+$/.test(name)){
                    result=$.isArray(result)?result:[];
                    result.push(util.__ObjToArray(data[name]));
                }else{
                    result[name]=util.__ObjToArray(data[name]);
                }
            }
        }else if(typeof data=="string"||typeof data=="number"||typeof data=="boolean"){
            result=data;
        }else{
            /*基本不会被运行到,需要优化*/
            result=$.isArray(result)?result:[];
            result=data;
        }
        return result;
    }
}
module.exports = util;