123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- /**
- * Expose the _EventTarget class.
- */
- module.exports = _EventTarget;
- function _EventTarget() {
- // Do nothing if called for a native EventTarget object..
- if (typeof this.addEventListener === 'function') {
- return;
- }
- this._listeners = {};
- this.addEventListener = _addEventListener;
- this.removeEventListener = _removeEventListener;
- this.dispatchEvent = _dispatchEvent;
- }
- Object.defineProperties(_EventTarget.prototype, {
- listeners: {
- get: function () {
- return this._listeners;
- }
- }
- });
- function _addEventListener(type, newListener) {
- var
- listenersType,
- i, listener;
- if (!type || !newListener) {
- return;
- }
- listenersType = this._listeners[type];
- if (listenersType === undefined) {
- this._listeners[type] = listenersType = [];
- }
- for (i = 0; !!(listener = listenersType[i]); i++) {
- if (listener === newListener) {
- return;
- }
- }
- listenersType.push(newListener);
- }
- function _removeEventListener(type, oldListener) {
- var
- listenersType,
- i, listener;
- if (!type || !oldListener) {
- return;
- }
- listenersType = this._listeners[type];
- if (listenersType === undefined) {
- return;
- }
- for (i = 0; !!(listener = listenersType[i]); i++) {
- if (listener === oldListener) {
- listenersType.splice(i, 1);
- break;
- }
- }
- if (listenersType.length === 0) {
- delete this._listeners[type];
- }
- }
- function _dispatchEvent(event) {
- var
- type,
- listenersType,
- dummyListener,
- stopImmediatePropagation = false,
- i, listener;
- if (!event || typeof event.type !== 'string') {
- throw new Error('`event` must have a valid `type` property');
- }
- // Do some stuff to emulate DOM Event behavior (just if this is not a
- // DOM Event object)
- if (event._yaeti) {
- event.target = this;
- event.cancelable = true;
- }
- // Attempt to override the stopImmediatePropagation() method
- try {
- event.stopImmediatePropagation = function () {
- stopImmediatePropagation = true;
- };
- } catch (error) {}
- type = event.type;
- listenersType = (this._listeners[type] || []);
- dummyListener = this['on' + type];
- if (typeof dummyListener === 'function') {
- dummyListener.call(this, event);
- }
- for (i = 0; !!(listener = listenersType[i]); i++) {
- if (stopImmediatePropagation) {
- break;
- }
- listener.call(this, event);
- }
- return !event.defaultPrevented;
- }
|