What is the difference between the custom event API provided by native JavaScript DOM and the publish and subscribe model implemented by yourself?

the first way: use CustomEvent provided natively by JavaScript to create custom events
for example, you can create:

var evt = new CustomEvent(type, {detail: msg, bubbles: true, cancelable: true});

then listen for and trigger a custom event

element.addEventListener("longpress", longpressFn);
element.dispatchEvent(evt);

the second way: simulate a custom event publish and subscribe object by yourself

var Event = (function() {
    var clientList = {};
    var listen,
        trigger,
        remove;
    listen = function(key, fn) {
        if (!clientList[key]) {
            clientList[key] = [];
        }
        clientList[key].push(fn);
    };

    trigger = function() {
        var key = [].shift.call(arguments);
        var fns = clientList[key];

        if (!fns || fns.length === 0) {
            return false;
        }

        for (var i = 0, fn; fn = fns[iPP];) {
            fn.apply(this, arguments);
        }
    };


    remove = function(key, fn) {
        var fns = clientList[key];

        // key
        if (!fns) {
            return false;
        }

        // fn(), key
        if (!fn) {
            fns && (fns.length = 0);
        }
        else {
            // 
            for (var i = fns.length - 1,_fn=fns[i]; i >= 0; i--) {
                if (_fn === fn) {
                    // 
                    fns.splice(i, 1);
                }
            }
        }
    };

    return {
        listen: listen,
        trigger: trigger,
        remove: remove
    }
}());

both of these two methods can implement the creation, listening, triggering and deletion of a custom event, but the difference is that the first is the API, provided by native DOM and the second is simulated by publish-subscribe mode. Is the way native DOM is created as a publish / subscribe model?
which is better to use in a real project? After looking up the data, it seems that there seems to be an IE compatibility problem with the API of native DOM.
are some large libraries or frameworks using the second custom event subscription system? (mainly recently in building their own wheels, I heard that this model can reduce the coupling of the code, want to learn. )


are you sure your subscription publication is all right? As far as I understand it, when it comes to subscription and publication combined with face objects, the simplest pattern should have at least three parts:

who publishes the message, the message itself, and the subscriber.

in the event mode of native dom, it is itself a subscription and publication mode.

1. The most basic interface, of every htmlElement class is eventTarget, that is, the "publisher". You can see mdn: here .
that is, HTMLElement has an inheritance chain, Element-Node-EventTarget. The EvetntTarget interface implements the method of sending messages, so native dom elements can send messages, that is, dom elements can act as "publishers".

2. In fact, according to the face object, each event is an instance of the Event class. Every time an event is triggered, a message Event instance is created, which is broadcast to the subscriber by the publisher, that is, the specified dom element.

Subscribers in the

3.dom model can simply understand that achievements are "event handlers" that we have registered. However, in fact, according to the dom standard, dom event subscribers also have an interface format: here . Once this format is satisfied, you can add listener to eventTarget. Every time an Event is emitted, whether you are a custom event or a real user interaction event, listener will be triggered.

the one you implemented yourself did not abstract these three parts. Of course, subscription publishers can subscribe to themselves, and messages are not exposed internally. It just feels like it's a blur.

in fact, subscriptions and publications that you implement yourself are available on the HTMLElement of each interface native JS. Just look at the latest listen method that you implemented yourself, which is the addEventListener;trigger method, which is dispatchEvent;remove is removeEventListener. And the one you implemented yourself doesn't abstract Event messages and subscribers.


well, is it time to start building wheels without even figuring out the relationship between design patterns and API?

the relationship between the two is irrelevant. Design pattern is a design pattern, which can be used in any language and any API,. It is "the foundation of reusable object-oriented software". The browser DOM event mechanism is an implementation of the "subscription pattern", and it's okay if you want to implement a subscription model yourself (but mostly observer mode).

it is recommended that the subject take a good look at the book "Design patterns" first.


there is no way to achieve asynchrony unless you use setTimeout emulation.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2b7ec-2bab6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2b7ec-2bab6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?