设计模式思想:发布订阅
单例设计模式、构造函数、promise设计模式……
设计模式不是代码,是一种设计思想。有效地进行管理代码
设计模式不是具体的某个知识点,是一种编程思想。
发布订阅:我未来要做什么事情
概念:在未来某一时刻我要去做很多事情,先把事情列出成计划清单,当时刻到来时一件一件按照清单执行。
其实是跟dom2级事件学的。


$.Callbacks



- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>subscribe</title>
- </head>
- <body>
- <button id="btn">点击我</button>
- <script>
- (function(){
- class Subscribe{
- constructor(){
- this.pond=[]
- }
- add(func){
- // 类型校验
- if(typeof func !=='function') return;
- const isExist=this.pond.some(item=>item === func);
- if(!isExist){
- this.pond.push(func)
- }
- }
- remove(func){
- const index=this.pond.findIndex(item===func)
- if(index>-1){
- this.pond(index,1)
- }
-
- }
- fire(...args){
- this.pond.forEach(func=>func.call(this,...args))
- }
-
- }
- function _Subscribe() {
- return new Subscribe()
- }
- window._Subscribe=_Subscribe;
- // return function () {
- // return new Subscribe();
- // }
- })();
- const s1=new _Subscribe();
- function fn1(){
- console.log(1)
- }
- function fn2(){
- console.log(2)
- }
- function fn3(){
- console.log(3)
- }
- s1.add(fn1)
- s1.add(fn1)
- s1.add(fn2)
- s1.add(fn3)
- btn.addEventListener('click',function () {
- s1.fire()
- })
- </script>
- </body>
- </html>
-
在添加移除中,产生的经典问题:数组塌陷问题

export default / import
真实项目中的应用场景:
某一时刻我要去做很多事情,先创建一个事件池,到那一时刻事件池通知执行;想做什么事情往事件池中加方法/移除方法,来管控整个业务逻辑。
promise用异步解决
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>subscribe</title>
- </head>
- <body>
- <button id="btn">点击我</button>
- <script>
- (function(){
- class Subscribe{
- constructor(){
- this.pond=[]
- }
- add(func){
- // 类型校验
- if(typeof func !=='function') return;
- const isExist=this.pond.some(item=>item === func);
- if(!isExist){
- this.pond.push(func)
- }
- }
- remove(func){
- const index=this.pond.findIndex(item=>item===func)
- if(index>-1){
- // this.pond.splice(index,1)
- this.pond[index]=null
- }
-
- }
- fire(...args){
- // this.pond.forEach((func,index)=>{
- //
- // })
- const length=this.pond.length;
- for(let i=0;i<length;i++){
- const func=this.pond[i]
- if(typeof func !== 'function'){
- // 此时去移除
- this.pond.splice(i,1)
- i--;
- continue;
- }
- func.call(this,...args)
- }
- }
-
- }
- function _Subscribe() {
- return new Subscribe()
- }
- window._Subscribe=_Subscribe;
- // return function () {
- // return new Subscribe();
- // }
- })();
- const s1=new _Subscribe();
- function fn1(){
- console.log(1)
- }
- function fn2(){
- console.log(2)
- s1.remove(fn1)
- }
- function fn3(){
- console.log(3)
- }
- function fn4(){
- console.log(4)
- }
- s1.add(fn1)
- // s1.add(fn1)
- s1.add(fn2)
- s1.add(fn3)
- s1.add(fn4)
- btn.addEventListener('click',function () {
- s1.fire()
- })
- </script>
- </body>
- </html>
-