class Observer {
constructor() {
this.listeners = []
}
notify(...args) {
this.listeners.forEach((cb) => {
cb.apply(this, args)
})
}
subscribe(cb) {
if (!(this.listeners.includes(cb))) {
this.listeners.push(cb)
}
}
unSubscribe(cb) {
this.listeners = this.listeners.filter((item) => item !== cb)
}
}
const ob = new Observer()
const test = (name) => { console.log('hello', name) }
ob.subscribe(test)
ob.unSubscribe(test)
ob.subscribe((name) => { console.log('world', name) })
ob.notify('ruijia')
class EventEmitter {
constructor() {
this.eventList = {}
}
on(name, cb) {
const flag = this.eventList[name]
if (!flag) {
this.eventList[name] = []
this.eventList[name].push(cb)
} else {
this.eventList[name].push(cb)
}
}
off(name, cb) {
const flag = this.eventList[name]
if (flag) {
this.eventList[name] = this.eventList[name].filter((item) => item != cb)
} else {
throw TypeError('need')
}
}
once(name, cb) {
const request = function (...args) {
cb.apply(null, args)
this.off(name, cb)
}
this.on(name, request)
}
emit(name, ...args) {
const flag = this.eventList[name]
if (flag) {
this.eventList[name].forEach((cb) => {
cb.apply(null, args)
})
}
}
}
function SuperType(name){
this.name = name
}
function SubType(name){
SuperType.call(this,name)
this.age = 20
}
SubType.prototype = new SuperType()
SubType.prototype.constructor = SubType
console