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?
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() .
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.
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.
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.
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');
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With