How are custom broadcast events implemented in JavaScript (or jQuery)?

会有一股神秘感。 提交于 2019-12-05 03:29:15

All right.

So I think what you can do is use the native dispatchEvent and addEventListener methods and use document as the only element for both publishing and subscribing to those events. Something like:

var myCustomEvent = new Event('someEvent');
document.dispatchEvent(myCustomEvent);
...
document.addEventListener('someEvent', doSomething, false);

And to make cross-browser, you could:

var myCustomEvent = new Event('someEvent');
document.dispatchEvent(myCustomEvent);
...
if (document.addEventListener) {
    document.addEventListener('someEvent', doSomething, false);
} else {
    document.attachEvent('someEvent', doSomething);
}

You can read more on the subject here and here. Hope this helps.

My question is: is there a better (or at least more standard) way to achieve this effect of "broadcasting" custom events?

No, there is not a more standard way of doing publish/subscribe in Javascript. It is not directly built into the language or the browser and there are no platform standards for it that I'm aware of.

You have several options (most of which you seem aware of) to put your own system together.

You could pick a specific object such as the document object or the window object or a new object you create and use jQuery's .on() and .trigger() with that object as a central clearing house to cobble together a publish/subscribe-like model. You could even hide the existence of that object from your actual use by just coding it into a few utility functions if you want.

Or, as you seem to already know, you could use the jQuery.Callbacks functionality. There's even publish/subscribe sample code in the jQuery doc.

Or, you can find a third party library that offers a somewhat traditional publish/subscribe model.

Or, you can build your own from scratch which really just involves keeping a list of callback functions that are associated with a specific event so when that event is triggered, you can call each callback function.

If you came here looking for the jQuery way of doing this, here you go:

Add the event broadcast/dispatch code:

Syntax:
$(<element-name>).trigger(<event-name>);.

Example:

$.ajax({
    ...
    complete: function () {
        // signal to registered listeners that event has occured
        $(document).trigger("build_complete");
        ...
    }
});

Register a listener for the event:

Syntax:
$(<element-name>).on(<event-name>, function() {...});

Example:

$(document).on("build_complete", function () {
    NextTask.Init();
});

Note: Doing it this way: $(document).build_complete(function() {...}); leads to an error: Uncaught TypeError: $(...).build_complete is not a function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!