const Center = { message: {}, publich(type, data) { if (!this.message[type]) return; this.message[type].forEach(item => item(data)) }, subscribe(type, cb) { if (!this.message[type]) { this.message[type] = [cb] } else { this.message[type].push(cb) } }, unSubscribe(type, cb) { if (!this.message[type]) return; this.message = this.message[type].filter(item => item != cb) } } function test1(data) { console.log('test1', data); } function test2(data) { console.log('test2', data); }
Center.subscribe('a', test1) Center.subscribe('b', test2) Center.subscribe('b', test1) Center.publich('a', 111) Center.publich('b', 222)
const Center = { message: {}, publich(type, data) { if (!this.message[type]) return; this.message[type].forEach(item => item(data)) }, subscribe(type, cb) { if (!this.message[type]) { this.message[type] = [cb] } else { this.message[type].push(cb) } }, unSubscribe(type, cb) { if (!this.message[type]) return; this.message = this.message[type].filter(item => item != cb) } } Center.subscribe('updateDOM', data => { document.querySelector('#bread').innerHTML = data }) news.addEventListener('click', (e) => { if (e.target.tagName == 'LI') { Center.publich('updateDOM', e.target.innerHTML) } })