common.js 9.04 KB
define('components/common', ['jquery'], function () {
    var storage = window.localStorage;

    Array.prototype.remove = function(index) {
        return !!this.splice(index, 1);
    }

    var isObject = type("Object");

    function type(typename) {
        return function(o) {
            return Object.prototype.toString.call(o) == '[object ' + typename + ']';
        };
    }

    var ajaxQueue = {};

	return {
		importCssText: function (id, cssText, doc, isreplace, onappend) {
            if(this.isBoolean(doc)) {
                onappend = isreplace;
                isreplace = doc;
                doc = document;
            }

            doc = doc || document;
            
            var  style = doc.getElementById( id + '.css' );

			if( style ) return isreplace && (style.innerHTML = cssText);

			style = doc.createElement('style');
			
			cssText += "\n/*# sourceURL=" + id + " */"; // 添加source URL 便于分清css来源
			style.appendChild( doc.createTextNode(cssText) );
            style.id = id + '.css';

            if (onappend) return onappend(style);

			doc.querySelector('head').appendChild(style);
		},
        tempEngine: function(template, data) {
        	var replace = function(pre, obj) {
				return pre + template.replace(/{{([\s\S]*?)}}/g, function(match, property) {
					var render = "with(this){ return " + property.trim() + "}";
					var _render = new Function(render).bind(obj);
					
					return _render();
            	});
        	}

        	if(this.isArray(data)) {
        		return data.reduce(replace, '');
        	}

        	return replace('', data);

        },
        isArray: type('Array'),
        isNumber: type('Number'),
        isObject: isObject,
        isBoolean: type('Boolean'),
        isFunction: type('Function'),
        isString: type('String'),
        getClass: function(str) {
            return '.' + str;
        },
        getId: function(str) {
            return '#' + str;
        },
        getPixel: function(num) {
            return num + 'px';
        },
        ajax: function(mod, settings, success, fail) {
            if(typeof mod == 'string') {
                settings.url = this.jionActionUrl("com.weaver.formmodel.admin." + mod,
                    "action=" + settings.action);    
            } else {
                success = settings;
                settings = mod;
            }

        	return $.ajax( $.extend({
        		type: 'post',
        		contentType: 'application/json',
                dataType: 'json',
                cache: false
        	}, settings) )
        	.done(function() {
        		success && success.apply(null, arguments);
        	})
        	.fail(function() {
        		fail && fail.apply(null, arguments);
        	});
        },
        api: function(mod, settings, success, fail) {
			/**
			 * settings 自定义参数
			 *  - $el 通过clsName来限制请求数始终唯一
             *  - clsName 与$el一起使用 默认为disabled
			 *  - force true 强制请求  false 返回deferred (当多条相同请求时使用)
			 *  - notification 提示信息 { success: "xxx", error: "xxx"}
			 */
            if(typeof mod == 'string') {
                settings.url = "/api/mobilemode/admin/" + mod + "/" + settings.action;    
            } else {
                success = settings;
                settings = mod;
            }

            var $el = settings.$el,
                clsName = settings.clsName || "disabled",
				_toggleCls = function() {
					$el && $el.toggleClass(clsName);
				};

			if($el && $el.hasClass(clsName)) return;

			_toggleCls();

			var hasforce = settings.hasOwnProperty("force");

			if(hasforce && !settings.force && ajaxQueue[settings.url]) {
				return ajaxQueue[settings.url];
			}
			var _notification = function(msg, issuccess) {
				if(settings.notification === false) return;
				require(["notification"], function(notification) {
					if(issuccess) {
						notification.success(msg);
					} else {
						notification.error(msg);
					}
				});
			};

			var _ajax = $.ajax( $.extend({
                    type: 'post',
                    dataType: 'json',
                    cache: false
				}, settings) )
				.done(function(res) {
					var api_errormsg = res.api_errormsg;
					var notification = settings.notification || {};

					if(res.api_status) {
						success && success.apply(null, arguments);
						notification.success && _notification(notification.success, true);
					} else {
                        fail && fail.apply(null, arguments);
                        
                        if(notification.error) {
                            _notification(notification.error);
                        } else {
						    api_errormsg = !api_errormsg ? "" : ", " + SystemEnv.getHtmlNoteName(5365) + ": " + api_errormsg;//异常信息
						    api_errormsg = api_errormsg.replace("catch exception : ", "");
                            
						    _notification(SystemEnv.getHtmlNoteName(5366) + api_errormsg);//服务器处理请求时出现异常
                        }

					}
					
					_toggleCls();
				})
				.fail(function() {
					fail && fail.apply(null, arguments);
                    _toggleCls();
					_notification(SystemEnv.getHtmlNoteName(5367));//请求服务器失败, 请稍后重试!
				});
			
			if(hasforce) {
				ajaxQueue[settings.url] = _ajax;
			}

			return _ajax;
        },
        getAppId: function() {
            return _appid || require('appdesigner').getAppId() || -1;
        },
        jionActionUrl: function(invoker, queryStr){
            if(!queryStr){
                queryStr = "";
            }
            if(queryStr.indexOf("&") != 0){
                queryStr = "&" + queryStr;
            }
            return "/mobilemode/Action.jsp?invoker=" + invoker + queryStr;
        },
        position: function (target, relative, position) { // 目标元素 和 相对定位的元素
            var toffset = target.offset(),
                pos = position || 'right',
                $body = $('body'),
                top, left, rh, rw;
            
            position = 0; // 定位在target元素下方
            rh = relative.outerHeight();
            rw = relative.outerWidth();
            top = toffset.top + target.outerHeight();

            switch(pos) {
                case 'right': // 居右
                    left = toffset.left + target.outerWidth() - rw; break;
                case 'left': // 居左
                    left = toffset.left; break;
                case 'center': // 居中
                    left = toffset.left + target.outerWidth() / 2 - rw / 2;
            }
            
            if(left + rw > $body.outerWidth()) {
                left = $body.outerWidth() - rw - 10;
            }

            if (top + rh > $body.outerHeight()) { // 定位在target元素上方
                top = toffset.top - rh;
                position = 1; // 上方
            }

            relative.css({ top: top, left: left });
            return position;
        },
        toInt: function(str) {
            str = str || '0';
            return parseInt( str.replace(/[^\d]/g, '') );
        },
        toLowerCase: function(str) {
            return (str || "").toLowerCase();
        },
        toId: function(id) {
            return '#' + id;
        },
        store: {
            get: function (itemName) {
                return storage && storage.getItem(itemName) || window[itemName];
            },
            set: function (itemName, value) {
                if (storage) {
                    value = isObject(value) ? JSON.stringify(value) : value;

                    return storage.setItem(itemName, value);
                }

                window[itemName] = value;
            },
            remove: function(itemName) {
                if(storage) return storage.removeItem(itemName);

                delete window[itemName];
            }
        },
        cookies: {
            get: function(key) {
                var reg = new RegExp("(^| )"+key+"=([^;]*)(;|$)"),
                    arr = document.cookie.match(reg);
                
                return arr && unescape(arr[2]) || null;
            },
            set: function(key, value) {
                var Days = 30; //此 cookie 将被保存 30 天
                var exp = new Date();
                exp.setTime(exp.getTime() + Days*24*60*60*1000);
                document.cookie = key + "="+ escape (value) + ";expires=" + exp.toGMTString();
            }
        },
        debounce: function (fn, delay) {
            var timer;

            return function () {
                var context = this;
                var args = arguments;

                clearTimeout(timer);

                timer = setTimeout(function () {
                    fn.apply(context, args);
                }, delay);
            }
        },
        getLanguage: function () {
            switch(_userLanguage) {
                case 7:
                    return "zh-CN";
                case 8:
                    return "en";
                case 9:
                    return "zh-TW";
                default: 
                    return "zh-CN";
            }
        }
	};
});