基于jQuery的事件绑定插件
遵循UMD规范,浏览器环境需支持ES6
使用说明
- 引用文件前需引入jQuery.js
- 第一个参数为需要绑定事件函数的对象
- 支持自定义属性绑定,属性前缀默认值为v,传值通过初始化第二个参数传入字符串
- 支持多种事件类型,传值通过初始化第三个参数传入数组,默认值为[‘click’, ‘dblclick’, ‘contextmenu’, ‘mousedown’, ‘mouseup’, ‘keyup’, ‘focus’, ‘blur’, ‘change’, ‘input’]
- 初始化插件方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<div>
<input type="text" v-input="doing"/>
<button class="btn" v-click="confirm">确认</button>
<button class="btn" v-dblclick="cancel">取消</button>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="./event_bind.js"></script>
<script type="text/javascript">
new $.eventBind({
doing() {
console.log('输入框正在输入...');
},
confirm() {
console.log('点击确认按钮');
},
cancel() {
console.log('双击取消按钮');
}
});
</script>
</html>
event_bind.js:
!function (root, factory) {
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = factory(require('jquery'));
} else if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function ($) {
$.extend({
eventBind: class {
constructor(fnObj, prefix, events) {
this.prefix = prefix || 'v';
this.events = events || ['click', 'dblclick', 'contextmenu', 'mousedown', 'mouseup', 'keyup', 'focus', 'blur', 'change', 'input'];
this.eventBind(fnObj);
}
eventBind (fnObj) {
let prefix = this.prefix,
events = this.events,
selector = events.map(e => `[${prefix}-${e}]`),
$eles = this.$eles = $(selector.join(',')),
attrBinds = this.attrBinds = {},
attrName = '',
attrValue = '',
eventType = '';
$eles.each(function () {
let attr;
for (let i = 0, len = events.length; i < len; i++) {
attr = this.attributes[`${prefix}-${events[i]}`];
if (attr) {
attrName = attr.name;
attrValue = attr.value;
eventType = events[i];
break;
}
}
if (!attr) {
console.warn('没有配置该事件类型', this);
return true;
}
if (!attrValue) {
console.warn(`${prefix}-${eventType}属性值不能为空`, this);
return true;
}
if (!fnObj[attrValue]) {
console.warn(`找不到事件绑定函数:${attrValue}()`);
return true;
}
if (typeof fnObj[attrValue] !== 'function') {
console.warn(`请声明正确的事件绑定函数:${attrValue}()`);
return true;
}
if (attrBinds[attrValue] && attrBinds[attrValue] == attrName) {
return true;
}
$($eles.context).off(eventType, `[${attrName}="${attrValue}"]`).on(eventType, `[${attrName}="${attrValue}"]`, $(this).data(), fnObj[attrValue].bind(fnObj));
attrBinds[attrValue] = attrName;
});
}
}
});
});
|