I\'m creating a client-side dynamic blog engine. Now I need a event system to handle many actions from DOM elements and the engine. Such as the engine is loading a article,user
Recently, I wanted to add simple event listeners to vanilla JavaScript objects. This is the solution I came up with
(This requires ecmascript >= 5
)
function Emitter () {
var eventTarget = document.createDocumentFragment();
function delegate (method) {
this[method] = eventTarget[method].bind(eventTarget);
}
Emitter.methods.forEach(delegate, this);
}
Emitter.methods = ["addEventListener", "dispatchEvent", "removeEventListener"];
Now a "class" that uses it
function Example () {
Emitter.call(this);
}
Let's try it out now!
var e = new Example();
e.addEventListener("something", function(event) {
alert("something happened! check the console too!");
console.log(event);
});
e.dispatchEvent(new Event("something"));
Good luck!