1.发布订阅
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);
2.观察者模式
- 什么是观察者模式
一种消息机制,解耦多个模块相互依赖,提供一种通信机制。
// 发布订阅模式
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();
3.二者的区别
- 发布订阅模式中,发布者订阅者是靠第三方来完成事件通信的。发布者发布事件到第三方,订阅者从第三方订阅事件。但是,观察者模式中,被观察者是直接触及观察者的