Can plain Javascript objects have events?
Not directly but you add the required publish/subscribe
infrastructure to any one of them.
No.
However, you could make your own implementation by writing addEventListener
and other functions and storing a list of handlers for each event.
For example: (Untested)
function addEventListener(name, handler) {
if (!this.events) this.events = {};
if (!this.events[name]) this.events[name] = [];
this.events[name].push(handler);
}
function removeEventListener(name, handler) {
if (!this.events) return;
if (!this.events[name]) return;
for (var i = this.events[name].length - 1; i >= 0; i--)
if (this.events[name][i] == handler)
this.events[name].splice(i, 1);
}
function raiseEvent(name, args) {
if (!this.events) return;
if (!this.events[name]) return;
for (var i = 0; i < this.events[name].length; i++)
this.events[name][i].apply(this, args);
}
var obj = ...;
obj.addEventListener = addEventListener;
obj.removeEventListener = removeEventListener;
obj.raiseEvent = raiseEvent;
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');
}
};