5. Events
优质
小牛编辑
131浏览
2023-12-01
完整地替代命名空间和事件代理,链接到 https://github.com/oneuijs/oui-dom-events
5.0 Document ready by
DOMContentLoaded
// jQuery
$(document).ready(eventHandler);
// Native
// 检测 DOMContentLoaded 是否已完成
if (document.readyState === 'complete' || document.readyState !== 'loading') {
eventHandler();
} else {
document.addEventListener('DOMContentLoaded', eventHandler);
}
5.1 使用 on 绑定事件
// jQuery
$el.on(eventName, eventHandler);
// Native
el.addEventListener(eventName, eventHandler);
5.2 使用 off 解绑事件
// jQuery
$el.off(eventName, eventHandler);
// Native
el.removeEventListener(eventName, eventHandler);
5.3 Trigger
// jQuery
$(el).trigger('custom-event', {key1: 'data'});
// Native
if (window.CustomEvent) {
const event = new CustomEvent('custom-event', {detail: {key1: 'data'}});
} else {
const event = document.createEvent('CustomEvent');
event.initCustomEvent('custom-event', true, true, {key1: 'data'});
}
el.dispatchEvent(event);