本文共 3316 字,大约阅读时间需要 11 分钟。
var publisherSubscriber = { };// we send in a container object which will handle the subscriptions and publishings(function(container) { // the id represents a unique subscription id to a topic var id = 0; // we subscribe to a specific topic by sending in // a callback function to be executed on event firing container.subscribe = function(topic, f) { if (!(topic in container)) { container[topic] = []; } container[topic].push({ "id": ++id, "callback": f }); return id; } // each subscription has its own unique ID, which we use // to remove a subscriber from a certain topic container.unsubscribe = function(topic, id) { var subscribers = []; for (var subscriber of container[topic]) { if (subscriber.id !== id) { subscribers.push(subscriber); } } container[topic] = subscribers; } container.publish = function(topic, data) { for (var subscriber of container[topic]) { // when executing a callback, it is usually helpful to read // the documentation to know which arguments will be // passed to our callbacks by the object firing the event subscriber.callback(data); } }})(publisherSubscriber);
// 发布订阅模式 const pubSub = (() => { // 这里是存储事件和其对应得回调函数 const subTopics = { }; // 订阅一个事件的时候,如果该事件不存在,那怎么办? // 那就注册该事件,并且传入回调函数 function subscrible (topic, callback) { if (!subTopics[topic]) { subTopics[topic] = []; } subTopics[topic].push(callback); } function publish (topic, ...args) { if (subTopics[topic].length) { for (let fnc of subTopics[topic]) { fnc(...args); } } } return { publish, subscrible } })() pubSub.subscrible('test', (a, b) => { console.log(( a + b )); }) pubSub.subscrible('test', (a, b) => { console.log(( a - b )); }) pubSub.publish('test', 1, 2); // 观察者模式 // 目标主体 class Subject { constructor () { this.sub = []; } addSub (ob) { this.sub.push(ob); } notify () { for (let ob of this.sub) { ob.update(); } } } // 观察者1 class Observer1 { update () { console.log('update1'); } } // 观察者2 class Observer2 { update () { console.log('update2'); } } const sub = new Subject(); const ob1 = new Observer1(); const ob2 = new Observer2(); sub.addSub(ob1); sub.addSub(ob2); sub.notify();
转载地址:http://fgthn.baihongyu.com/