Handwritten publishing subscription

class EventEmitter {
	constructor(){
		this.events = {}
	}
	// A method to subscribe to events
	on(eventName,callback){
		if(this.events[eventName]){
			this.events[eventName].push(callback)
		}else{
			this.events[eventName] = [callback]
		}
	}
	// The method that triggers the event
	emit(eventName){
		this.events[eventName] && this.events[eventName].forEach(cb= > cb())
	}
	// Remove subscription events
	removeListener(eventName,callback){
		if(this.events[eventName]){
			this.events[eventName] = this.events[eventName].filter(cb= >cb ! == callback) } }// Execute subscribed events only once, then remove
	once(eventName,callback){
		let fn = () = > {
			callback()
			this.removeListener(eventName,fn)
		}
		this.on(eventName,fn)
	}
}
Copy the code

Handwritten singleton mode

/ / instance to do judgment
// Use closures to ensure that instances are not lost (closures prolong the lifetime of variables)
// Execute the function immediately
const Login = (function(){
	function Login(state){
    	this.state = state
    }
    Login.prototype.show(){
    	console.log(state)
    }
    
    let instance = null
    return function Single(. args){
    	if(! instance){ instance =newLogin(... args) }return instance
    }
})()

//
const Login = (function(){
	class Login {
    	constructor(state){
        	this.state = state
        }
        
        show(){
    		console.log(state)
    	}
    }
	
    let instance = null
    return function Single(. args){
    	if(! instance){ instance =newLogin(... args) }return instance
    }
})()
Copy the code

Class form, can refer to:

const Login = (function(){
	class Login{
		constructor(state){
			this.state = state
		}

		show(){
			console.log(this.state)
		}
	}

	let instance = null
	return function Sington(. args){
		if(! instance){ instance =newLogin(... args) }return instance
	}

})()
Copy the code

Blog.csdn.net/weixin_4396…