trigger custom event without jQuery

独自空忆成欢 提交于 2019-11-29 03:22:17

If you want an exact replication of jQuery's behaviour, you're probably best off digging through the jQuery source code.

If you just want to do normal event dispatching and listening, see CustomEvent for how to dispatch an event with custom data and addEventListener for how to listen to it.

Your example would probably look something like

document.addEventListener('hey', function(customEvent)
{
    console.log(customEvent.type + ' ' + customEvent.detail.user); // hey stackoverflow
});
document.dispatchEvent(new CustomEvent('hey', {'detail': {'user': 'stackoverflow'}}));

You can use Custom Events and dispatch them on element you want.

The quick & easy way:

$('#element').trigger("mycustomevent");

or for global event:

$(document).trigger("mycustomevent");

catching it:

$('#element').on("mycustomevent", function(e){
    // do something
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!