发布订阅模式(观察者模式)
发布订阅模式的定义:它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。
发布订阅模式在JS中最常见的就是DOM的事件绑定与触发:
//todo 注册点击事件btn.addEventListener("click", function (event) { console.log("点击事件触发了");});//todo 执行点击事件btn.click();这两句代码就是该模式的核心:注册了点击事件,在某个特定时刻(这里是按钮点击)执行注册的事件。
在vue的事件绑定里用到了
在vue里的事件注册也是用的该模式,这里是vue里绑定事件的模仿:
class VueEvent { constructor() { this.callbakcs = Object.create(null); } on(type, cb) { if (!(type in this.callbakcs)) { this.callbakcs[type] = []; } this.callbakcs[type].push(cb); return this; } off(type, fn) { if (!(type && fn)) { this.callbakcs = Object.create(null); } else if (type && !fn) { delete this.callbakcs[type]; } else { const thisTypeCBs = this.callbakcs[type]; for (const key in thisTypeCBs) { if (fn == thisTypeCBs[key] || fn == thisTypeCBs[key].fn) { thisTypeCBs.splice(key, 1); } } } return this; } once(type, cb) { const _this = this; function innerOnce(...arg) { cb(...arg); _this.off(type, innerOnce); } innerOnce.fn = cb; this.on(type, innerOnce); return this; } emit(type, ...arg) { if (type in this.callbakcs) { const runs = [...this.callbakcs[type]]; //! 深复制 下面的循环里有可能会删除数组元素 for (const cb o......原文转载:http://www.shaoqun.com/a/873523.html
跨境电商:https://www.ikjzd.com/
wario:https://www.ikjzd.com/w/887
文化衫事件:https://www.ikjzd.com/w/1932
review:https://www.ikjzd.com/w/2735
发布订阅模式(观察者模式)发布订阅模式的定义:它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。发布订阅模式在JS中最常见的就是DOM的事件绑定与触发://todo注册点击事件btn.addEventListener("click",function(event){console.log("点击事件触发了");}
airwallex:https://www.ikjzd.com/w/1011
泡温泉需要泡多久时间最好?:http://www.30bags.com/a/400246.html
泡温泉要注意什么?:http://www.30bags.com/a/397788.html
泡温泉要注意什么事项?:http://www.30bags.com/a/401005.html
泡温泉要准备什么?:http://www.30bags.com/a/400136.html
男朋友在车里㖭我全身 男生技术好是一种体验:http://lady.shaoqun.com/m/a/248255.html
妇女上厕所正面尿尿 学校女厕所真实图片:http://lady.shaoqun.com/m/a/246669.html
女人喜欢男人㖭 女人喜欢被㖭是什么感觉:http://lady.shaoqun.com/m/a/247876.html
不注意这点,订单再多也是白干!原来跨境大卖们在用它……:https://www.ikjzd.com/articles/146592
女人偷偷和同事在野外约会"亲密"老公用卫生纸抓奸(图):http://lady.shaoqun.com/a/418109.html
90%的男生阅历很深,女生有那么多"随便"的意思?:http://lady.shaoqun.com/a/419109.html
轮皮公园成了"野战圣地",曼谷政府严惩讲和的公共场所!:http://lady.shaoqun.com/a/419110.html
没有评论:
发表评论