Observer pattern and js custom events

Event is a design pattern called observer, which consists of two types of objects: subject and observer. The principal is responsible for publishing events, and the observer observes the principal by subscribing to these events. Take DOM for example, DOM is the body, and event handling code is the observer.

Here is a custom event,

function EventTarget() {
			this.handlers = {};
		}
		EventTarget.prototype = {
			constructor: EventTarget,
			addHandler: function (type, handler) {
				if (typeof this.handlers[type] == 'undefined') {
					this.handlers[type] = [];
				}
				this.handlers[type].push(handler);
			},
			fire: function (event) {
				if (!event.target) {
					event.target = this;
				}
				if (this.handlers[event.type] instanceof Array) {
					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;
						}
					}
					handlers.splice(i, 1);
				}
			}
		}
Call of custom event, addHandler() add event, fire() execute event, removeHandler() delete bound event.

function handleMessage1(event) {
			console.log("111--", event.message);
		}
		function handleMessage2(event) {
			console.log("222--", event.message);
		}
		var target = new EventTarget();
		// Add event
		target.addHandler('message', handleMessage1);
		target.addHandler('message', handleMessage2);
		// Execution event
		target.fire({
			type: 'message',
			message: 'hello!'
		})

		// Delete event
		target.removeHandler('message', handleMessage1);
		// Execution event
		target.fire({
			type: 'message',
			message: 'holy'
		})

Posted on Sun, 03 May 2020 11:57:31 -0700 by tourer