SOURCE

class Subject{
    constructor(){
        this.observers=[]
    }
    addObserver(data){
        this.observers.push(data)
    }
    removeObserver(data){
        this.observers=this.observers.filter(observer=>observer!==data)
    }
    notify(data){
        this.observers.forEach(observer=>observer.update(data))
    }
}
class Observer{
    constructor(name){
        this.name=name
    }
    update(data){
        console.log('数据更新了',data)
    }
}
// 示例用法
const subject = new Subject();

const observer1 = new Observer('观察者1');
const observer2 = new Observer('观察者2');

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.notify('新数据更新了'); 
subject.removeObserver(observer1);

subject.notify('又有新数据更新了'); 
console 命令行工具 X clear

                    
>
console