Safari EventTarget Interface

I started expanding the interface EventTargetby adding some useful ones prototypes, but then I tested it on Safari 8 and got:

[Error] ReferenceError: Can't find variable: EventTarget

I found in MDN that for does not exist window.EventTarget. "

This question looks really interesting, but it concerns IE8.

So, I want to know if a link to the EventTarget interface on Safari is available or a workaround for using type code EventTarget.prototype.hasEventListenerand EventTarget.prototype.hasEventListenerwithout any errors in Safari?

Edit I found an interesting commit that says it was implemented on 09/12/15 (from a timestamp), but it is sure that it does not work in Safari 9.1

+5
source share
2 answers

Workaround:

I just used the Elementinterface as a backup for Safari

var EventTarget = EventTarget || Element;
EventTarget.prototype.addEventListener = function(){/*Some magic here*/};

I also verified that Element inherits prototypesfrom the EventTarget interface, and it does! ( document.body.addEventListener == EventTarget.prototype.addEventListenerreturned true)

+3
source

Safari simply does not allow you to use the interface EventTargetin your own objects, except for DOM elements. So I just copied the class to do this.

class EventDispatcher {

    constructor() {
        this._listeners = [];
    }

    hasEventListener(type, listener) {
        return this._listeners.some(item => item.type === type && item.listener === listener);
    }

    addEventListener(type, listener) {
        if (!this.hasEventListener(type, listener)) {
            this._listeners.push({type, listener, options: {once: false}});
        }
        // console.log('${this}-listeners:',this._listeners);
        return this
    }

    removeEventListener(type, listener) {
        let index = this._listeners.findIndex(item => item.type === type && item.listener === listener);
        if (index >= 0) this._listeners.splice(index, 1);
//        console.log('${this}-listeners:', this._listeners);
        return this;
    }

    removeEventListeners() {
        this._listeners = [];
        return this;
    }

    dispatchEvent(evt) {
        this._listeners
            .filter(item => item.type === evt.type)
            .forEach(item => {
                const {type, listener, options: {once}} = item;
                listener.call(this, evt);
                if (once === true) this.removeEventListener(type, listener)
            });
        // console.log('${this}-listeners:',this._listeners);
        return this
    }
}
+1
source

All Articles