JS设计模式-发布订阅模式

JS设计模式-发布订阅模式

1.什么是发布订阅模式

"一对多的关系"

btn.addEventListener('click',fn1)
btn.addEventListener('click',fn2)
btn.addEventListener('click',fn3)

当初发点击事件时,上述绑定的三个函数都将执行

2.

var salesOffice = {}
salesOffice.clientList = {}
salesOffice.listen = function(type,fn){
    if(!this.clientList[type]) this.clientList[type] = []
    this.clientList[type].push(fn)
}
salesOffice.trriger = function(){
    var type = Array.prototype.shift.call(arguments)
    for(var i = 0; i<this.clientList[type].length; i++) this.clientList[type][i].apply(this,arguments)
}
//zhangsan
salesOffice.listen('square88',function(price,squareMetter){
    console.log('zhangsan');
    console.log(price)
    console.log(squareMetter);
})
//lisi
salesOffice.listen('square88',function(price,squareMetter){
    console.log('lisi');
    console.log(price)
    console.log(squareMetter);
})
//wangwu
salesOffice.listen('square108',function(price,squareMetter){
    console.log('wangwu');
    console.log(price)
    console.log(squareMetter);
})
//zhaoliu
salesOffice.listen('square108',function(price,squareMetter){
    console.log('zhaoliu');
    console.log(price)
    console.log(squareMetter);
})
salesOffice.trriger('square88',10000,88)

抽象解释一下

square88,square108:事件的类型

salesOffice.listen:用于绑定监听事件的函数

salesOffice.trriger:触发事件的函数

salesOffice.clientList:保存所有绑定事件的容器

3.封装

对下方的代码进行一个封装

var salesOffice = {}
salesOffice.clientList = {}
salesOffice.listen = function(type,fn){
    if(!this.clientList[type]) this.clientList[type] = []
    this.clientList[type].push(fn)
}
salesOffice.trriger = function(){
    var type = Array.prototype.shift.call(arguments)
    for(var i = 0; i<this.clientList[type].length; i++) this.clientList[type][i].apply(this,arguments)
}

封装后

var Event = {
    clientList:{},
    listen:function(type,fn){
        if(!this.clientList[type]) this.clientList[type] = []
        this.clientList[type].push(fn)
    },
    trriger:function(){
        var type = Array.prototype.shift.call(arguments)
        for(var i = 0; i<this.clientList[type].length; i++) 
            this.clientList[type][i].apply(this,arguments)
    }
}
function installEvent(readyOne,tool){
    for(var i in tool) readyOne[i] = tool[i]
    return readyOne
}
var salesOffice={};
salesOffice = installEvent(salesOffice,Event)

通过installEvent即可使一个对象满足发布订阅模式的yaoqiu

4.面向对象封装

class Event{
    constructor(){
        this.clientList = {}
    }
    listen(type,fn) {
        if(!this.clientList[type]) this.clientList[type] = []
        this.clientList[type].push(fn)
    }
    trriger(){
        var type = Array.prototype.shift.call(arguments)
        for(var i = 0; i<this.clientList[type].length; i++) 
            this.clientList[type][i].apply(this,arguments)
    }

}
class SalesOffice extends Event{
    constructor(){
        super()
    }
}
var salesOffice=new SalesOffice();

对象继承

上一篇:自制标签组件


下一篇:自定义包和可见性