JavaScript项目中封装的util常用工具

/**
 *
 * @authors dongtao
 * @date    2017-02-20 11:15:01
 * @version 1.0.0
 * 公有方法
 */

var utils = utils || {};
! function($) {
	//记录前端日志
	function webLogs(params) {
		var cache = common.getLocalStorage('autoClaim.ss.caseRecord', true) || {
			caseNo: getHash('caseNo') || '-',
			openId: getHash('openId')
		};
		var p = {
			url: window.location.href || '', //当前页面名称
			type: 0, //日志类别
			content: '无内容', //日志内容
			caseNo: cache.caseNo, //案件号
			openID: cache.openId //微信唯一编号
		};
		if (typeof params === 'string') {
			p.content = params;
		} else {
			$.extend(p, params);
		}

		$.post(server() + '/wx/waitAuditing/webLogs', p, function(response) {
			var res = response;
		});
	}

	//获取当前页面的名称
	function getPageName() {
		var pathname = window.location.pathname;
		var index = pathname.lastIndexOf('\/');
		if (index > 0) {
			pathname = pathname.substr(index + 1);
		}
		return pathname;
	}

	//记录本地日志,用于本地开发和测试
	function log(msg) {
		var _d = new Date();
		var s = _d.getFullYear() + '-' + (_d.getMonth() + 1) + '-' + _d.getDate() + ' ' + _d.getHours() + ':' + _d.getMinutes() + ':' + _d.getSeconds();
		var _tit = '[' + s + '(' + getPageName() + ')] ' + msg;
		sessionStorage._mobile_log = (sessionStorage._mobile_log || '') + _tit + '<br/>';

		webLogs(_tit);
		console && console.log && console.log(_tit);
	}

	//判断是否为undefined
	function isUndefined(o) {
		return typeof o === 'undefined';
	}

	//判断是否为数组类型
	function isArray(o) {
		return o !== null && typeof o === 'object' && 'splice' in o && 'join' in o;
	}

	//判断是否为object类型
	function isObject(o) {
		return typeof o === 'object';
	}

	//判断是否为string类型
	function isString(o) {
		return typeof o === 'string';
	}

	//判断是否为boolean类型
	function isBoolean(o) {
		return typeof o === 'boolean';
	}

	//判断对象是否为空字符串,去除前后空格
	function isBlank(o) {
		o = o || '';
		return o === '' || o.trim() === '';
	}

	//重定向,页面跳转
	function redirection(path) {
		window.location.href = path || '/pages/404.html';
	}

	//获取地址栏参数
	function getHash(key, url) {
		var hash;
		if (!!url) {
			hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
			hash = (hash == url) ? "" : hash;
		} else {
			hash = self.location.search;
		}

		hash = "" + hash;
		hash = hash.replace(/^[?#]/, '');
		hash = "&" + hash;
		var val = hash.match(new RegExp("[\&]" + key + "=([^\&]+)", "i"));
		if (!val || val.length < 1) {
			return null;
		} else {
			return decodeURIComponent(val[1]);
		}
	}

	//接口地址
	function server() {
		return window.location.protocol + '//' + window.location.host + '/ch5';
	}

	//文件是否存在
	function isInclude(path) {
		var index = path.lastIndexOf('\/');
		var name = index > 0 ? path.substr(index + 1) : path;
		var css = /css$/i.test(name);
		var tag = 'link';
		var pt = 'href';
		if (!css) {
			tag = 'script';
			pt = 'src';
		}

		var elements = document.getElementsByTagName(tag);
		for (var i = 0; i < elements.length; i++) {
			if (elements[i][pt].indexOf(name) > -1) {
				return true;
			}
		}
		return false;
	}

	//动态加载文件,只能加载CSS和js文件
	function loadFiles(path, callback, js) {
		var el = document.getElementsByTagName('body')[0];
		var node = document.createElement('script');
		if (js) {
			node.type = 'text/javascript';
			node.src = path;
		} else {
			el = document.getElementsByTagName('head')[0];
			node = document.createElement('link');
			node.rel = 'stylesheet';
			node.type = 'text/css';
			node.href = path;
		}
		//所有浏览器加载css都会走onload方法
		node.onload = function() {
			if (js) {
				callback({
					status: true
				});
			} else {
				var _n = 0;
				var _poll = function(node, callback) {
					var isLoaded = false;
					if (/webkit/i.test(navigator.userAgent)) {
						//webkit
						if (node.sheet) {
							isLoaded = true;
						}
					} else if (node.sheet) {
						// for Firefox
						try {
							if (node.sheet.cssRules) {
								isLoaded = true;
							}
						} catch (ex) {
							// NS_ERROR_DOM_SECURITY_ERR
							if (ex.code === 1000) {
								isLoaded = true;
							}
						}
					}
					if (isLoaded) {
						callback({
							status: true
						});
					} else {
						if (++_n > 10) {
							callback({
								status: false,
								error: 'CSS文件加载失败,请重试...'
							});
						} else {
							window.setTimeout(function() {
								_poll(node, callback);
							}, 100);
						}
					}
				};

				_poll(node, callback);
			}
		};
		node.onerror = function(e) {
			callback({
				status: false,
				error: (js ? 'script' : 'CSS') + '文件加载时发生错误,请重试...'
			});
		};

		el.appendChild(node);
	}

	//动态加载css文件
	function loadStyle(path, callback) {
		if (!$.isFunction(callback)) return;
		if (!path || path.length === 0) {
			callback({
				status: false,
				error: '请传入有效的路径'
			});
		}
		var exist = isInclude(path);
		if (exist) {
			callback({
				status: true
			});
		} else {
			loadFiles(path, callback);
		}
	}

	//动态加载js文件
	function loadScript(path, callback) {
		if (!$.isFunction(callback)) return;
		if (!path || path.length === 0) {
			callback({
				status: false,
				error: '请传入有效的路径'
			});
		}
		var exist = isInclude(path);
		if (exist) {
			callback({
				status: true
			});
		} else {
			loadFiles(path, callback, true);
		}
	}

	function getAddress(lat, lang, callback) {
		var _path = window.location.protocol + '//webapi.amap.com/maps?v=1.3&key=585d5dd703232d5bf2311e7b03882824';
		loadScript(_path, function(response) {
			if (response.status) {
				var n = 0;
				var t = window.setInterval(function() {
					n++;
					if (window.AMap && AMap.service) {
						window.clearInterval(t);
						t = null;
						AMap.service('AMap.Geocoder', function() {
							//回调函数
							//实例化Geocoder
							geocoder = new AMap.Geocoder({
								city: "010" //城市,默认:“全国”
							});
							//TODO: 使用geocoder 对象完成相关功能
							var lnglatXY = [lang, lat]; //地图上所标点的坐标
							geocoder.getAddress(lnglatXY, function(status, result) {
								if (status === 'complete' && result.info === 'OK') {
									//获得了有效的地址信息:
									log('获取具体地理位置成功返回信息:' + result.regeocode.formattedAddress);
									if ($.isFunction(callback)) {
										callback(result.regeocode.formattedAddress);
									}
								} else {
									//获取地址失败
									log('获取具体地理位置失败返回信息:' + JSON.stringify(result));
									callback('');
								}
							});
						});
					}
					//如果5s后还未获取成功,则返回空
					if (n > 10) {
						window.clearInterval(t);
						t = null;
						log('获取具体地理位置失败返回信息:5s后都没有找到AMap.service');
						callback('');
					}
				}, 500);
			} else {
				common.Prompt(response.error);
				callback('');
			}
		});
	}

	//非法请求判断
	function illegalEntry() {
		//判断流程是否完整
		var _re = document.referrer || '';
		if (_re) {
			//当在QQ里时,document.referrer等于当前主机名,但是这两个值又不相等,不知道怎么解决
			//统一判断是否带有上下文
			_re = _re.indexOf('wxic') > -1 ? 1 : '';
		}
		var _c = window.location.href.indexOf('cp.com.cn') > -1; //排除本地开发环境

		if (_re === '' && _c) {
			window.location.replace('../pages/share.html');
		}
	}

	var common = common || {};

	//设置本地缓存
	common.setLocalStorage = function(key, value, isJson) {
		if (window.localStorage) {
			if (isJson) {
				value = JSON.stringify(value);
			}
			window.localStorage[key] = value;
		} else {
			log("当前浏览器不支持localStorage");
		}
	};

	//获取本地缓存
	common.getLocalStorage = function(key, isJson) {
		if (window.localStorage) {
			var value = window.localStorage[key] || "";
			if (isJson && value) {
				value = JSON.parse(value);
			}
			return value;
		} else {
			log("当前浏览器不支持localStorage");
		}
	};

	//清除本地缓存
	common.removelocalStorage = function(key) {
		log("移除localStorage数据key=" + key);
		if (window.localStorage) {
			window.localStorage.removeItem(key);
		} else {
			log("当前浏览器不支持localStorage");
		}
	};

	//增加cookie
	common.addCookie = function(name, value, expiresHours) {
		var cookieString = name + "=" + escape(value);
		//判断是否设置过期时间
		if (expiresHours) {
			if (expiresHours > 0) {
				var date = new Date();
				date.setTime(date.getTime + expiresHours * 3600 * 1000);
				cookieString = cookieString + "; expires=" + date.toGMTString();
			}
		}
		document.cookie = cookieString;
	};

	//获取cookie
	common.getCookie = function(name) {
		var strCookie = document.cookie;
		var arrCookie = strCookie.split("; ");
		for (var i = 0; i < arrCookie.length; i++) {
			var arr = arrCookie[i].split("=");
			if (arr[0] == name) return arr[1];
		}
		return "";
	};

	//删除cookie
	common.deleteCookie = function(name) {
		var date = new Date();
		date.setTime(date.getTime() - 10000);
		document.cookie = name + "=v; expires=" + date.toGMTString();
	};

	//二秒后消失的弹出框
	common.Prompt = function(message) {
		if (!message) {
			message = '网络异常,请稍后重试...';
		}
		if ($('#e_ui_prompt').size() > 0) return;
		var _fontSize = $('body').css('font-size') || '36px';
		if (window.location.href.indexOf('smallChange.html') > -1) {
			_fontSize = '1.4rem';
		}
		//创建prompt框样式
		var type = "width:80%;padding:15px 0;border-radius:15px; color:#fff; background-color:#6c6c6c; text-align:center;font-size:" + _fontSize + "; opacity:0;position:fixed;top:75%;left:10%;z-index:100000;";
		//创建prompt框
		var h = $("<div style='" + type + "' id='e_ui_prompt'>" + message + "</div>");
		$('body').append(h);

		//改变透明度
		var i = 0;
		var t = window.setInterval(function() {
			i = i + 0.1;
			if (i >= 1) {
				window.clearInterval(t);
				t = null;
				i = 0;
			} else {
				$(h).css('opacity', i);
			}
		}, 80);

		//2秒后消失
		window.setTimeout(function() {
			var j = $(h).css('opacity');
			var ti = window.setInterval(function() {
				j = j - 0.1;
				if (j <= 0) {
					window.clearInterval(ti);
					ti = null;
					$(h).remove();
				} else {
					$(h).css('opacity', j);
				}
			}, 80);
		}, 2000);
	};

	//自适应移动设备
	common.adaptivePhone = function() {
		var content = '';
		var meta = document.createElement('meta');
		meta.name = "viewport";

		if (/Android (\d+\.\d+)/.test(navigator.userAgent)) {
			var version = parseFloat(RegExp.$1);
			if (version > 2.3) {
				var phoneScale = parseInt(window.screen.width) / 750;
				content = 'width=750, minimum-scale = ' + phoneScale + ', maximum-scale = ' + phoneScale + '';
				meta.onload = function(e) {
					log('viewport完成');
				};
			} else {
				content = 'width=750';
			}
		} else {
			content = 'width=750, user-scalable=no';
		}
		document.head.appendChild(meta);
		meta.setAttribute('content', content);
	};

	//是否为空
	common.isNull = function(value) {
		if (value) {
			return false;
		}
		return true;
	};

	//是否不为空
	common.isNotNull = function(value) {
		return !common.isNull(value);
	};

	function Map() {
		this.elements = new Array();

		//获取MAP元素个数
		this.size = function() {
			return this.elements.length;
		};

		//判断MAP是否为空
		this.isEmpty = function() {
			return (this.elements.length < 1);
		};

		//删除MAP所有元素
		this.clear = function() {
			this.elements = new Array();
		};

		//向MAP中增加元素(key, value)
		this.put = function(_key, _value) {
			this.elements.push({
				key: _key,
				value: _value
			});
		};

		//删除指定KEY的元素,成功返回True,失败返回False
		this.remove = function(_key) {
			var bln = false;
			try {
				for (i = 0; i < this.elements.length; i++) {
					if (this.elements[i].key == _key) {
						this.elements.splice(i, 1);
						return true;
					}
				}
			} catch (e) {
				bln = false;
			}
			return bln;
		};

		//获取指定KEY的元素值VALUE,失败返回NULL
		this.get = function(_key) {
			try {
				for (i = 0; i < this.elements.length; i++) {
					if (this.elements[i].key == _key) {
						return this.elements[i].value;
					}
				}
			} catch (e) {
				return null;
			}
		};

		//获取指定索引的元素(使用element.key,element.value获取KEY和VALUE),失败返回NULL
		this.element = function(_index) {
			if (_index < 0 || _index >= this.elements.length) {
				return null;
			}
			return this.elements[_index];
		};

		//判断MAP中是否含有指定KEY的元素
		this.containsKey = function(_key) {
			varbln = false;
			try {
				for (i = 0; i < this.elements.length; i++) {
					if (this.elements[i].key == _key) {
						bln = true;
					}
				}
			} catch (e) {
				bln = false;
			}
			return bln;
		};

		//判断MAP中是否含有指定VALUE的元素
		this.containsValue = function(_value) {
			var bln = false;
			try {
				for (i = 0; i < this.elements.length; i++) {
					if (this.elements[i].value == _value) {
						bln = true;
					}
				}
			} catch (e) {
				bln = false;
			}
			return bln;
		};

		//获取MAP中所有VALUE的数组(ARRAY)
		this.values = function() {
			var arr = new Array();
			for (i = 0; i < this.elements.length; i++) {
				arr.push(this.elements[i].value);
			}
			return arr;
		};

		//获取MAP中所有KEY的数组(ARRAY)
		this.keys = function() {
			var arr = new Array();
			for (i = 0; i < this.elements.length; i++) {
				arr.push(this.elements[i].key);
			}
			return arr;
		};
	}

	//日志展示
	function _mobileLog() {
		if ($('#_mobileBtn').size() === 0) {
			var tlp = [];
			tlp.push('<div style="width:100%;height:100%;background:rgba(0,0,0,0.8);position:fixed;top:0;left:0;z-index:99999;">');
			tlp.push('<p style="width:100%;height:' + ($(window).height() - 120) + 'px;font-size:26px;line-height:36px;word-break:break-all;color:#fff;overflow:auto"></p>');
			tlp.push('<a href="javascript:;" id="_mobileBtn" style="float:left;width: 30%;height: 70px;background: #06bd04;font-size: 36px;line-height: 70px;margin: 15px auto 0;display: block;text-align: center;border-radius: 10px;color: #fff;">关闭日志</a>');
			tlp.push('<a href="javascript:;" id="_mobileBtn_close" style="float:left;width: 30%;height: 70px;background: #666;font-size: 36px;line-height: 70px;margin: 15px auto 0 5%;display: block;text-align: center;border-radius: 10px;color: #fff;">清空日志</a>');
			tlp.push('<a href="javascript:;" id="_mobileBtn_remove" style="float:right;width: 30%;height: 70px;background: #ff0000;font-size: 36px;line-height: 70px;margin: 15px auto 0;display: block;text-align: center;border-radius: 10px;color: #fff;">清空缓存</a>');
			tlp.push('</div>');
			$('body').append(tlp.join(''));
			$('#_mobileBtn').prev('p').html(sessionStorage._mobile_log || '无');
			//关闭事件
			$('#_mobileBtn').on('click', function() {
				$(this).parent().remove();
			});
			//清空日志
			$('#_mobileBtn_close').on('click', function() {
				sessionStorage._mobile_log = '';
				$('#_mobileBtn').prev('p').html('');
				$('#_mobileBtn').parent().remove();
			});
			//清除缓存
			$('#_mobileBtn_remove').on('click', function() {
				alert('将清空本地全部缓存');
				window.localStorage.clear();
				window.sessionStorage.clear();
			});
		}
	}

	//获取页面错误消息
	/**
	 * @param {String} errorMessage  错误信息
	 * @param {String} scriptURI   出错的文件
	 * @param {Long}  lineNumber   出错代码的行号
	 * @param {Long}  columnNumber  出错代码的列号
	 * @param {Object} errorObj    错误的详细信息,Anything
	 */
	window.onerror = function(errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {
		log("<strong style='color:red'>****************************************</strong>");
		log("错误信息:" + errorMessage);
		log("出错文件:" + scriptURI);
		log("出错行号:" + lineNumber);
		log("出错列号:" + columnNumber);
		log("错误详情:" + errorObj);
		log("<strong style='color:red'>****************************************</strong>");
	};


	//根据不同环境显示日志按钮
	function _showLog() {
		var showFlag = isShowOrNot();
		if (showFlag) {
			$('body').append('<div id="_mobile_log_mark" style="width:90px;height:60px;border:1px solid #ddd;border-radius: 0 20px 20px 0;background:rgba(0,0,0,0.2);line-height:60px;font-size:30px;color:#fff;text-align:center;font-weight:600;position:fixed;bottom:0;left:0;z-index:99996;">LOG</div>');
			//打开事件
			$('#_mobile_log_mark').on('click', function(event) {
				_mobileLog();
			});
		}
	}

	//特定条件显示log和
	function isShowOrNot() {
		var _openIDs = ['oAl3ejopthT-F_gXaXtiWeWlSYtA', 'oAl3ejnALwJL0tkgO8hC2I8ib3_c', 'oAl3ejsuElGxqZ_fOboKER8R76AI', 'oAl3ejpyMhGB8ZgkkRgS-URfc3qg', 'oAl3ejhtSwxyKJ5pH2KrZ5IO_Q9s', 'oAl3ejtfoUAogv0T_vN8GKVaovUw', 'oAl3ejv6_P15A4kt-w18d-HP0lm4', 'oAl3ejtfQ25eZYRI2xPd9Mn_u6eo','oAl3ejksiZ0XknBgKp33e0p0RtwM','oAl3ejsn1DI6YVpvbdikniDyF9vk'];
		var _openid = getHash('openid') || '';
		if (_openid) {
			sessionStorage._exist_log = _openid;
		} else {
			_openid = sessionStorage._exist_log;
		}
		var _exist = $.inArray(_openid, _openIDs) > -1;
		var _host = window.location.hostname;
		if (_host.indexOf("ftsurvey") > -1 || (_host.indexOf('surveysit') > -1 && _exist)) {
			return true;
		}
		return false;
	}

	//配置是否启用开关
	function builtSwitck() {
		/*
		 * 配置开关选项类
		 * */
		this.optionSwitch = {};
		/*
		 * 本地数据开关
		 * true 时 用户的ajax请求使用的是本地的模拟数据
		 *
		 * */
		var locData = false;
		/*
		 * ajax请求默认方法(用于开关的转换)
		 * */
		var ajaxrequestfn = null;
		Object.defineProperty(this.optionSwitch, 'locData', {
			set: function(a) {
				//ajax没有加载好时,等待。
				var ajax = window.ajax || 0;
				if (!ajax) {
					var lazytime = setTimeout(function() {
						clearTimeout(lazytime);
						this.optionSwitch.locData = a;
					}, 1500);
					return;
				}

				if (typeof a !== "boolean") return;
				locData = a;
				ajaxrequestfn = ajax.request;
				if (a) {
					log('本地数据开关开启');
					//获取ajax修改默认方法
					ajax.request = function(param, callback) {
						//准备加载本地数据
						loadScript('../components/utils/localData.js', function(response) {
							if (response.status) {
								window.setTimeout(function() {
									if (window.localdataobj) {
										localdataobj.paselocaldata(param, function(data) {
											if (data.status) {
												var backdata = data.responseBody;
												//返回数据
												callback({
													status: '000000',
													responseBody: backdata
												});
											} else {
												//打印错误信息,执行默认ajax方法
												log(data.message);
												ajaxrequestfn.call(ajax, param, callback);
											}
										});
									}
								}, 2000);
							}
						});
					};
				} else {
					log('本地数据开关关闭');
					//如果没有执行过set value=true方法不做处理
					if (!locData) return;
					//重新恢复ajax请求
					ajax.request = function(param, callback) {
						ajaxrequestfn.call(ajax, param, callback);
					};
				}
			},
			get: function() {
				return locData;
			}
		});
	}

	//自定义执行函数
	$(function() {
		//显示日志
		_showLog();
		//点击事件监听
		utils.loadScript('../components/libs/jqlog.js', function(response) {});
	});

	var Switck = new builtSwitck();

	utils = {
		log: log,
		isUndefined: isUndefined,
		isArray: isArray,
		isObject: isObject,
		isString: isString,
		isBoolean: isBoolean,
		isBlank: isBlank,
		redirection: redirection,
		server: server,
		common: common,
		getHash: getHash,
		map: Map,
		loadStyle: loadStyle,
		loadScript: loadScript,
		getAddress: getAddress,
		webLogs: webLogs,
		illegalEntry: illegalEntry,
		optionSwitch: Switck.optionSwitch,
		mobileLog: _mobileLog,
		getPageName: getPageName,
		showTakeVideo: isShowOrNot
	};
}(window.Zepto, utils);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Vue ,我们可以通过自定义指令的方式来封装一个公共的 `oninput` 工具函数。 1. 在项目创建一个新的文件夹,例如 directives,用于存放自定义指令的代码。 2. 在 directives 文件夹创建一个新的文件,例如 `oninput.js`,用于编写 `oninput` 指令的代码。 3. 在 `oninput.js` 定义 `oninput` 指令的行为: ```javascript export const oninput = { mounted(el, binding) { el.oninput = (event) => { binding.value(event.target.value); }; }, updated(el, binding) { el.value = binding.value; }, }; ``` 在上面的代码,我们定义了 `oninput` 指令的两个钩子函数,分别是 `mounted` 和 `updated`。`mounted` 钩子函数在指令绑定到元素上时调用,用于绑定 `oninput` 事件处理器,并在输入内容发生变化时触发 `binding.value` 函数。`updated` 钩子函数在指令所在的组件更新后调用,用于更新输入框的值。 4. 在需要使用 `oninput` 指令的组件,通过以下方式引入: ```javascript import { oninput } from '@/directives/oninput.js'; ``` 5. 在组件的 `directives` 选项注册 `oninput` 指令: ```javascript export default { directives: { oninput, }, methods: { handleInput(value) { console.log(value); }, }, template: ` <input v-oninput="handleInput"> `, }; ``` 在上面的代码,我们在组件的 `directives` 选项注册了 `oninput` 指令,并在模板使用 `v-oninput` 指令将 `handleInput` 函数绑定到输入框上。当输入框的值发生变化时,`handleInput` 函数会被调用,传入输入框的值。 通过以上步骤,我们就可以封装一个公共的 `oninput` 工具函数,并在需要使用的组件引入和注册。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值