js简单粗暴的发布订阅

使用场景

异步通信、多页面间相互通信,pageA 的方法想在 pageB的方法调用的某个时机触发

直接上代码

class Publish {
    constructor() {
        this.listMap = {};
    }
	// 订阅
    on(key, fn) {
        this.listMap[key]
            ? this.listMap[key].push(fn)
            : this.listMap[key] = [fn];
            
		// 存储订阅fn的下标
        const index = this.listMap[key].length - 1;
        
		// 返回取消订阅的function
        return () => this.clear(key, index);
    }
    
	// 取消所有该key订阅
    off(key) {
        delete this.listMap[key];
    }
    
	// 取消key的指定的某个订阅
    clear(key, index) {
        index === this.listMap[key].length - 1
            ? this.listMap[key].pop()
            : this.listMap[key][index] = null;
    }
    
	//订阅一次触发后自动取消订阅
    once(key, fn) {
        this.on(key, (...rest) => {
            fn(...rest);
            this.off(key);
        });
    }

	// 发布key
    trigger(key, ...rest) {
    	if(key in this.listMap) {
	    	this.listMap[key].forEach(fn => {
	            fn(...rest);
	        });
    	}
    }
}

使用方法

const ob = new Publish();

// 订阅 sub1
const sub1 = ob.on('sub1', (a, b) => {
     
    console.log('sub1', a, b);
});

// 订阅 sub1
const sub11 = ob.on('sub1', (a, b) => {
     
    console.log('sub11', a, b);
});

ob.trigger('sub1', 2, 3);

// 取消订阅sub1
sub1();

// 取消订阅sub11
sub11();

// 订阅 sub3
ob.on('sub3', (a, b) => {
     
    console.log('sub3', a, b);
});

// 订阅 sub3
ob.on('sub3', (a, b) => {
     
    console.log('sub33', a, b);
});

ob.trigger('sub3', 6, 7);

// 取消订阅所有的sub3
ob.off('sub3');

// 订阅一次就自行取消订阅
ob.once('sub4', (a, b) => {
     
    console.log('sub4', a, b);
});

ob.trigger('sub4', 8, 9);

你可能感兴趣的:(js,小程序,vue)