5. Events

优质
小牛编辑
131浏览
2023-12-01

完整地替代命名空间和事件代理,链接到 https://github.com/oneuijs/oui-dom-events

  • 5.0 Document ready by DOMContentLoaded

    1. // jQuery
    2. $(document).ready(eventHandler);
    3. // Native
    4. // 检测 DOMContentLoaded 是否已完成
    5. if (document.readyState === 'complete' || document.readyState !== 'loading') {
    6. eventHandler();
    7. } else {
    8. document.addEventListener('DOMContentLoaded', eventHandler);
    9. }
  • 5.1 使用 on 绑定事件

    1. // jQuery
    2. $el.on(eventName, eventHandler);
    3. // Native
    4. el.addEventListener(eventName, eventHandler);
  • 5.2 使用 off 解绑事件

    1. // jQuery
    2. $el.off(eventName, eventHandler);
    3. // Native
    4. el.removeEventListener(eventName, eventHandler);
  • 5.3 Trigger

    1. // jQuery
    2. $(el).trigger('custom-event', {key1: 'data'});
    3. // Native
    4. if (window.CustomEvent) {
    5. const event = new CustomEvent('custom-event', {detail: {key1: 'data'}});
    6. } else {
    7. const event = document.createEvent('CustomEvent');
    8. event.initCustomEvent('custom-event', true, true, {key1: 'data'});
    9. }
    10. el.dispatchEvent(event);