Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can plain Javascript objects have events?

Can plain Javascript objects have event attached to them? Say something like this:

obj = new Object();
obj.addEventListener('doSomething', foo, true);

I know i can do this with jQuery, but is it possible without any library?

like image 624
NilColor Avatar asked Jan 18 '10 15:01

NilColor


People also ask

What are plain JavaScript objects?

In vanilla JavaScript a POJO (Plain Old JavaScript Object) is the simplest kind of object you could possibly have: a set of key-value pairs, created by the {} object literal notation or constructed with new Object() .

Is event a JavaScript object?

When a W3C event listener's event occurs and it calls its associated function, it also passes a single argument to the function—a reference to the event object. The event object contains a number of properties that describe the event that occurred.

Can a JavaScript object contain a function?

Object properties can be both primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.

How do you add a click event to a button with plain JavaScript?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.


1 Answers

You'll have to implement your own functionality for that, but that's not very hard.

var obj = {
    events: {},
    addEventListener: function(eventName, handler) {
        if(!(eventName in this.events))
            this.events[eventName] = [];

        this.events[eventName].push(handler);
    },

    raiseEvent: function(eventName, args) {
        var currentEvents = this.events[eventName];
        if(!currentEvents) return;

        for(var i = 0; i < currentEvents.length; i++) {
           if(typeof currentEvents[i] == 'function') {
              currentEvents[i](args);
           }
        }
    },

    click: function() {
        // custom 'click' function. when this is called, you do whatever you
        // want 'click' to do. and then raise the event:

        this.raiseEvent('onClick');
    }
};
like image 197
David Hedlund Avatar answered Oct 06 '22 00:10

David Hedlund