/ *
JavaScript design patterns, originally as follows; Observe mode requires that observers wishing to receive the ruler must subscribe to events that change content. The Subscribe/Publish pattern uses a topic/event channel between the subscriber and the publisher. The event system allows code to define application-specific events that can pass custom parameters that contain values required by the subscriber. The goal is to avoid dependency between subscribers and publishers.
It differs from the observer pattern in that it allows any subscriber to execute the appropriate event handlers to register and receive notifications from the publisher.
In observer mode, the target object is responsible for maintaining the observer. In a publish/subscribe model, publishers don’t care about subscribers, they just throw messages out. In observer mode, the observer needs to provide an interface. This interface is then called to align its state with the target state when the target object changes. That is to say, all observers need a unified interface, (such as the update method, unified the update method) publish/subscriber, the subscriber events trigger is not dependent on such an interface, 20 subscribers by listening to a particular message (the news generally contain name and subscribers required parameters) to trigger can be understood as, Instead of listening to the publisher, the subscriber listens to the message pool. Fires whenever there are messages it cares about in the message pool. No matter who posted this message */
class Observe{ constructor() { this.handlers = {}; Register (type, hander) {register(type, hander) {if (! This. Handlers. HasOwnProperty (type)) {enclosing handlers [type] = []} this. Handlers [type]. Push (hander) return this} / / trigger events emit(... args) { let type = Array.prototype.shift.call(args) if (this.handlers.hasOwnProperty(type)) { // console.log(this.handlers[type]) this.handlers[type].forEach(item => { // console.log(item) item.apply(item, args) }); } else { throw new Error(`${type} event isn't register`) } return this } } let observe = new Observe(); Observe. register('hello', function(a) {console.log(a)}) observe.emit('hello',[1,2,4]) observe.emit('word',2)Copy the code
// Observer mode
function ObserveList() {
this.observeList = [];
}
Copy the code
// Add a method to the observer
ObserveList.prototype.add = function (obj) {
return this.observeList.push(obj);
}
Copy the code
// Count the number of observers
ObserveList.prototype.count = function () {
return this.observeList.length;
}
Copy the code
// Get the specific observer in the current observer
ObserveList.prototype.get = function (index) {
if (index > -1 && index < this.observeList.length) {
return this.observeList[index]
}
}
Copy the code
// Get the index in the observer
ObserveList.prototype.indexOf = function (obj, startIndex) {
let i = startIndex || 0;
while(i < this.observeList.length) {
if (this.observeList[i] === obj) {
return i
}
i++
}
return -1
}
Copy the code
// Remove the current observer
ObserveList.prototype.removeAt = function (index) {
this.observeList.splice(index, 1);
}
Copy the code
// // The object of the observer, the observed
function Subject() {
this.observes = new ObserveList();
}
Copy the code
// Add an observer
Subject.prototype.addObserve = function (observe) {
this.observes.add(observe)
}
Copy the code
// Remove an observed method
Subject.prototype.removeObserve = function (observe) {
this.observes.removeAt(this.observes.indexOf(observe, 0))
}
Copy the code
// If the value in the observer changes, the corresponding subscriber to the event is notified
Subject.prototype.notify = function (context) {
let observeCount = this.observes.count();
for(let i = 0; i < observeCount; i++) {
this.observes.get(i).update(context)
}
}
Copy the code
/ / observer
Function ObserveGil() {this.update = function (context) {console.log(' first girlfriend found '+ context)}} function ObserveGil1() Update = function (context) {console.log(' second girlfriend found '+ context)}} function ObserveGil2() {this.update = function (context) {console.log(' second girlfriend found' + context)}} function ObserveGil2() {this.update = Function (context) {console.log(' third girlfriend found '+ context)}}Copy the code
// // Specific usage
let mySubject = new Subject(); mySubject.addObserve(new ObserveGil()); mySubject.addObserve(new ObserveGil1()); mySubject.addObserve(new ObserveGil2()); MySubject. Notify (' I am going to whorehouse today ')Copy the code
// Publish subscribers
let publish = {}; (function (myObject) {// Define the message queue let Topics = {}; // add a unique identifier let subUid = -1 for each added subscriber; Myobject.publish = function (topic, args) {if (! topics[topic]) { return false } let subscribers = topics[topic]; let len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func(topic, args) } return this; } myObject.subscribe = function (topic, func) {// Check if the message exists, create a storage space if (! Topics [topic]) {topics[topic] = []} let token = (++subUid).toString(); topics[topic].push({ token: token, func: func }) return token; } myObject.unSubscribe = function (token) {for (const key in topics) {if (topics. HasOwnProperty (key)) { const element = topics[key]; for(let i = 0; i < element.length; i++) { if (element[i].token === token) { topics[key].splice(i, 1) return token } } } } return this } })(publish); Publish.subscribe ('test', () => {console.log(' registered and executed method in publish subscriber ')}); publish.publish('test')Copy the code