js实现一个简单的订阅模式

订阅模式应用非常广泛,比如Vue中的钩子以及Vuex的设计模式中都大量使用了订阅模式。下面就简单的演示一下。


class Event {constructor() {this.handlers = {} // 事件队列}// 注册事件(发布)addEventListener(name, handler) {if (!(name in this.handlers)) {this.handlers[name] = []}this.handlers[name].push(handler) // 存入事件}// 触发事件(订阅)dispatch(name, ...params) {if (name in this.handlers) {this.handlers[name].forEach(h => {h(...params)})} else {throw Error('You need add event the first')}}// 移除事件remove(name) {if (name in this.handlers) {delete this.handlers[name]}}
}const event = new Event()
function log(message) {console.log(message)
}
event.addEventListener('log', log)
// event.remove('log')
event.dispatch('log', 'Haha') // Haha


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部