Event model is a type of observer pattern
The principle is that an object can publish an event when a particular state appears in its life cycle, and other objects can observe the object and wait for those special states to react when they occur. The observer pattern consists of two types of objects: Subject: The Observer that is responsible for publishing events: The Observer is responsible for observing subject, and by subscribing to those events it is important to note that subject does not know any information about observer, It can run as usual even if the observer does not exist. But Observer is aware of subject and registers event handle for events it publishes, such as when you are working with a DOM, the DOM element is subject,event handle is observer. Events are often used when interacting with the DOM, but event patterns can also be used in non-dom cases through custom events: the principle is to manage events by creating an object, allowing other objects to listen for examples of these events: function Eventtarget () { This.handlers = {}; Used to save event handle} Eventtarget.prototype = {constructor:eventtarget,
addhandler:function (type, handler) {
if (typeof this.handlers[type] = = "undefined") {When the event type is present, it is added to the array of the corresponding type.
t His.handlers[type] = [];
}
This.handlers[type].push (handler);
},
Fire:function (event) {
if (!event.target) {
event.target = this;
}
if (This.handlers[event.type] instanceof Array) {See the event handle for the corresponding events type, and then one by one call this handle
var handlers = This.handlers[event.type];
for (var i=0, len=handlers.length; i < Len; i++) {
Handlers[i] (event);
}
}
},removehandler:function (type, handler) {
if (This.handlers[type] instanceof Array) {
var handlers = This.handlers[type];
for (var i=0, len=handlers.length; i < Len; i++) {
if (handlers[i] = = = Handler) {
Break
; When you find the event handle that needs to be deleted, exit the For loop and remove the handle from the events callback array
.
}
}
Handlers.splice (i, 1);
}
}
}; How to use: Function Handlemessage (event) {alert ("Message Received:" + event.message);} var target = new Eventtarget (); Target.addhandler ("message", Handlemessage); Target.fire ({type: "message", Message: " Hello world! "}); Target.removehandler ("message", handlemessage);
Customizing event Watcher Patterns