A
A
Alexey Nagaev2017-01-09 17:05:21
JavaScript
Alexey Nagaev, 2017-01-09 17:05:21

What is an event in a javaScript object?

According to the literature, all js objects consist of properties and methods (properties to which functions are assigned), each property has its own attributes (Configurable, Enumerable, Writable, Value), these attributes can be viewed using the Object.getOwnPropertyDescriptor method, however, objects DOM, for example, the Element object, there are also events, for example, onscroll, so when I try to look at the attributes of this event, then undefined is returned to me. Hence the question, so what is an event in the context of an object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Gromov, 2017-01-09
@Pathgk

The literature describes what is available for use by site developers. Things like the DOM are part of the browser and are written using low-level code and internal features that are not exposed to developers for various reasons. It is likely that the event model for DOM elements is also written internally. Although it is not difficult to implement this pattern in pure JavaScript:

class Element {
    constructor() {
        this._events = {};
    }

    addEventListener(event, listener) {
        let listeners = this._events[event];

        if (!listeners) {
            listeners = this._events[event] = [];
        }

        listeners.push(listener);
    }

    removeEventListener(event, listener) {
        const listeners = this._events[event];

        if (listeners) {
            const index = listeners.indexOf(listener);

            if (index !== -1) {
                listeners.splice(index, 1);
            }
        }
    }

    dispatchEvent(event) {
        const listeners = this._events[event];

        if (listeners) {
            for (let listener of listeners) {
                listener(event);
            }
        }
    }
}

Using Map, you can completely get rid of the pseudo-private property _events and store it associatively.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question