0
点赞
收藏
分享

微信扫一扫

JavaScript 手写实现 Event-Bus

前言:

        今天给大家分享一下手写 Event-Bus,希望对大家有所帮助!

代码:

		function EventBus() {
			this._events = {};
		}
		EventBus.prototype.on = function (eventId, func) {
			const callbacks = this._events[eventId];
			if (!callbacks) {
				this._events[eventId] = [func];
				return;
			}
			callbacks.push(func);
		};
		EventBus.prototype.once = function (eventId, func) {
			const wrapper = ()=>{
				func();
				this.remove(eventId,wrapper)
			}
			const callbacks = this._events[eventId];
			if (!callbacks) {
				this._events[eventId] = [wrapper];
				return;
			}
			callbacks.push(wrapper);
		};
		EventBus.prototype.emit = function (eventId, ...args) {
			const callbacks = this._events[eventId];
			if (!callbacks) {
				return;
			}
			callbacks.forEach((fn) => {
				fn(args);
			});
		};
		// 只能删除被命名的函数
		EventBus.prototype.remove = function (eventId, fn) {
			const callbacks = this._events[eventId];
			if (!callbacks) {
				return;
			}
			callbacks.forEach((item, index) => {
				if (item === fn) {
					callbacks.splice(index, 1);
				}
			});
		};
		const fn1 = function () {
			console.log("fn1,fn1,fn1");
		};
		const fn2 = function () {
			console.log("should run once");
		};
		let eventbus = new EventBus();
		eventbus.on("sayHi", fn1);
		eventbus.once("sayHi", fn2);
		eventbus.emit("sayHi");
		eventbus.emit("sayHi");
		// eventbus.remove("sayHi", fn1);
		console.log(eventbus);
举报

相关推荐

0 条评论