目录
前言
其中简单描述了一下JavaScript中发布订阅模式的实现,但是个人觉得其中的方法过于单一,于是想尝试拓展一下,做个简易版的消息中心
起步
参考node中的 events事件触发器 我总结归类出了以下函数
- on :注册事件
- emit:触发事件
- un:事件销毁
- once:注册事件,执行后即销毁
- clear:重置事件列表(消息中心)
- has:判断事件是否被订阅
- handlerLength:返回某个事件的监听函数数量
- watch:与on一样,不同点是可以将结果返回至发布者
- invoke:与emit一样,配合watch使用,当watch中存在异步操作时接收其结果
功能设计
了解了实现的功能,我们把类的接口实现一下,其中events是之前文章中的调度中心,使用一个对象来存取所有绑定的事件
export declare interface Handlers {
[key: string]: Array<Function>
}
export declare interface IMessageCenter {
events: Handlers
_instance?: IMessageCenter
on: (type: string, handler: Function) => this
emit: (type: string, data?: any) => this
un: (type: string, handler?: Function) => this
once: (type: string, handler: Function) => this
clear: () => this
has: (type: string) => boolean
handlerLength: (type: string) => number
watch: (

本文介绍了如何实现一个简易版的消息中心,基于发布订阅模式,包括注册事件、触发事件、销毁事件、只执行一次的事件等功能。同时,还提供了异步操作支持和事件数量查询。文章通过JavaScript实现了一个消息中心类,并给出了实例验证。
https://hunter1024.blog.youkuaiyun.com/article/details/113770950
最低0.47元/天 解锁文章
456





