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
You could implement mediator pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mediatorpatternjavascript
In this book is everything you need to know about it.
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!
class SimpleEvent {
constructor() {
this.onEvent = {}
this.handler = function(funct, name) {
var owner = this
var name = name
this.onEvent[name] = funct
var remove = function() {
delete this.owner.onEvent[this.name]
delete this.owner
delete this.name
delete this.remove
}
if ((((!(remove == undefined && name == undefined)) && (remove == undefined || name == undefined)))) {
throw new Error("-_-")
} else {
return (remove == undefined || name == undefined) ? (undefined) : ({
remove: remove,
name: name
})
}
}
}
Fire() {
for (var i in this.onEvent) {
this.onEvent[i](arguments)
}
}
}