问题
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 is switching a theme...
And I don't want to use a library to do this.
So far I've done is using a list to store callbacks for a event.
But I want each callback works with different objects.Like the DOM event.
I may add an id-like property to each object, and store (id,callbacks) in a event.I feel it's not so good.When comes with dynamically generated object,it could be complex to deal with.
How to implement it as simple as DOM event (to use)?
回答1:
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!
回答2:
You could implement mediator pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mediatorpatternjavascript
In this book is everything you need to know about it.
回答3:
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)
}
}
}
来源:https://stackoverflow.com/questions/24342784/how-to-implement-a-complete-event-system-with-javascript