【JS】js订阅发布模式

js订阅发布模式

liaoxinyu发布于 今天 11:49

interface IEvents {

[key: string]: Array<Function>

}

class EventListener {

events: IEvents

constructor() {

this.events = {}

}

listen(key, fn) {

let fns = this.events[key];

if (fns) {

fns.push(fn)

} else {

this.events[key] = [fn]

}

}

on(key, payload) {

const fns = this.events[key]

if (fns && fns.length > 0) {

const fn = fns.shift()

fn(payload)

}

}

remove(key, fn) {

const fns = this.events[key]

if (!Array.isArray(fns)) return

const index = fns.indexOf(fn)

if (index !== -1) {

fns.splice(index, 1)

}

}

}

let listener = new EventListener()

const fetch1 = () => {

setTimeout(() => {

const res = {

current: 'fetch1',

next: 'fetch2'

}

console.log(res)

listener.on('fetch2', res)

})

}

const fetch2 = (payload) => {

setTimeout(() => {

const res = {

current: payload.next,

next: 'fetch3'

}

console.log(res)

listener.on('fetch3', res)

})

}

const fetch3 = (payload) => {

console.log({

current: payload.next,

next: ''

})

}

listener.listen('fetch2', fetch2)

listener.listen('fetch3', fetch3)

fetch1()

javascript

阅读 42更新于 今天 11:50

本作品系原创,采用《署名-非商业性使用-禁止演绎 4.0 国际》许可协议

avatar

liaoxinyu

前端开发.

15 声望

4 粉丝

0 条评论

得票时间

avatar

liaoxinyu

前端开发.

15 声望

4 粉丝

宣传栏

interface IEvents {

[key: string]: Array<Function>

}

class EventListener {

events: IEvents

constructor() {

this.events = {}

}

listen(key, fn) {

let fns = this.events[key];

if (fns) {

fns.push(fn)

} else {

this.events[key] = [fn]

}

}

on(key, payload) {

const fns = this.events[key]

if (fns && fns.length > 0) {

const fn = fns.shift()

fn(payload)

}

}

remove(key, fn) {

const fns = this.events[key]

if (!Array.isArray(fns)) return

const index = fns.indexOf(fn)

if (index !== -1) {

fns.splice(index, 1)

}

}

}

let listener = new EventListener()

const fetch1 = () => {

setTimeout(() => {

const res = {

current: 'fetch1',

next: 'fetch2'

}

console.log(res)

listener.on('fetch2', res)

})

}

const fetch2 = (payload) => {

setTimeout(() => {

const res = {

current: payload.next,

next: 'fetch3'

}

console.log(res)

listener.on('fetch3', res)

})

}

const fetch3 = (payload) => {

console.log({

current: payload.next,

next: ''

})

}

listener.listen('fetch2', fetch2)

listener.listen('fetch3', fetch3)

fetch1()

以上是 【JS】js订阅发布模式 的全部内容, 来源链接: www.h5w3.com/113105.html

回到顶部