class Subject { constructor() { this.observers = [] } add(obj) { this.observers.push(obj) } remove(obj) { this.observers = this.observers.filter(item => item != obj) } notify() { this.observers.forEach(item => item.update()) } } class Observer { constructor(name) { this.name = name } update() { console.log(this.name + ' updated'); } }
let ob1 = new Observer('gl') let ob2 = new Observer('sh') let sub = new Subject() sub.add(ob1) sub.add(ob2) sub.notify()
class Subject { constructor() { this.observers = [] } add(obj) { this.observers.push(obj) } remove(obj) { this.observers = this.observers.filter(item => item != obj) } notify(str) { this.observers.forEach(item => item.update(str)) } } class Observer { constructor(name) { this.el = document.querySelector(name) } update(str) { this.el.innerHTML = str } } let sub = new Subject() let obj = new Observer('#bread') sub.add(obj) news.addEventListener('click', (e) => { if (e.target.tagName == 'LI') { sub.notify(e.target.innerHTML) } })