Introduction
The observer mode is also called the publish/subscribe mode (Publish/Subscribe). It defines a one-to-many relationship, allowing multiple observer objects to monitor a certain topic object at the same time. When the status of the topic object changes, All observer objects will be notified so that they can update themselves automatically.
Benefits of using the observer pattern:
1. Support simple broadcast communication and automatically notify all subscribed objects.
2. After the page is loaded, the target object can easily have a dynamic relationship with the observer, which increases flexibility.
3. The abstract coupling relationship between the target object and the observer can be independently extended and reused.
Text (version 1)
The implementation of the observer pattern in JS is achieved through callbacks. Let's first define a pubsub object, which contains 3 methods: subscribe, unsubscribe, and publish.
var pubsub = {};
(function (q) {
var topics = {}, // Array stored in callback function
subUid = -1;
//Publish method
q.publish = function (topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function () {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
//Subscription method
q.subscribe = function (topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = ( subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
//How to unsubscribe
q.unsubscribe = function (token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i ) {
If (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
} (pubsub));
Use as follows:
//Come and subscribe
pubsub.subscribe('example1', function (topics, data) {
console.log(topics ": " data);
});
//Publish notification
pubsub.publish('example1', 'hello world!');
pubsub.publish('example1', ['test', 'a', 'b', 'c']);
pubsub.publish('example1', [{ 'color': 'blue' }, { 'text': 'hello'}]);
How about it? Isn’t it great to use? But there is a problem with this method, that is, there is no way to unsubscribe. If you want to unsubscribe, you must specify the name of the unsubscription, so let’s come up with another version:
//Assign the subscription to a variable to unsubscribe
var testSubscription = pubsub.subscribe('example1', function (topics, data) {
console.log(topics ": " data);
});
//Publish notification
pubsub.publish('example1', 'hello world!');
pubsub.publish('example1', ['test', 'a', 'b', 'c']);
pubsub.publish('example1', [{ 'color': 'blue' }, { 'text': 'hello'}]);
//Unsubscribe
setTimeout(function () {
pubsub.unsubscribe(testSubscription);
}, 0);
//Publish again to verify whether the information can still be output
pubsub.publish('example1', 'hello again! (this will fail)');
Version 2
We can also use the characteristics of prototypes to implement an observer pattern. The code is as follows:
function Observer() {
This.fns = [];
}
Observer.prototype = {
Subscribe: function (fn) {
This.fns.push(fn);
},
unsubscribe: function (fn) {
This.fns = this.fns.filter(
function (el) {
If (el !== fn) {
}
}
);
},
Update: function (o, thisObj) {
var scope = thisObj || window;
This.fns.forEach(
function (el) {
el.call(scope, o);
}
);
}
};
//Test
var o = new Observer;
var f1 = function (data) {
console.log('Robbin: ' data ', get to work quickly!');
};
var f2 = function (data) {
console.log('Randall: ' data ', ask him to increase his salary!');
};
o.subscribe(f1);
o.subscribe(f2);
o.update("Tom is back!")
//Unsubscribe f1
o.unsubscribe(f1);
//Verify again
o.update("Tom is back!");
If you are prompted that the filter or forEach function cannot be found, it may be because your browser is not new enough and currently does not support the new standard functions. You can define it yourself using the following method:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, thisObj) {
var scope = thisObj || window;
for (var i = 0, j = this.length; i < j; i) {
fn.call(scope, this[i], i, this);
}
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (fn, thisObj) {
var scope = thisObj || window;
var a = [];
for (var i = 0, j = this.length; i < j; i) {
If (!fn.call(scope, this[i], i, this)) {
continue;
}
a.push(this[i]);
}
return a;
};
}
Version 3
If we want multiple objects to have the observer publish and subscribe function, we can define a general function, and then apply the function of this function to the objects that need the observer function. The code is as follows:
//General code
var observer = {
//Subscribe
AddSubscriber: function (callback) {
This.subscribers[this.subscribers.length] = callback;
},
//Unsubscribe
removeSubscriber: function (callback) {
for (var i = 0; i < this.subscribers.length; i ) {
If (this.subscribers[i] === callback) {
delete (this.subscribers[i]);
}
}
},
//Publish
publish: function (what) {
for (var i = 0; i < this.subscribers.length; i ) {
If (typeof this.subscribers[i] === 'function') {
This.subscribers[i](what);
}
}
},
// Make object o have observer function
Make: function (o) {
for (var i in this) {
o[i] = this[i];
o.subscribers = [];
}
}
};
Then subscribe to two objects blogger and user, and use the observer.make method to make these two objects have observer functions. The code is as follows:
var blogger = {
Recommend: function (id) {
var msg = 'Posts recommended by dudu:' id;
This.publish(msg);
}
};
var user = {
vote: function (id) {
var msg = 'Someone voted! ID=' id;
This.publish(msg);
}
};
observer.make(blogger);
observer.make(user);
The usage method is relatively simple. Subscribe to different callback functions so that you can register to different observer objects (you can also register to multiple observer objects at the same time):
var tom = {
Read: function (what) {
console.log('Tom saw the following message: ' what)
}
};
var mm = {
show: function (what) {
console.log('mm saw the following information: ' what)
}
};
// Subscribe
blogger.addSubscriber(tom.read);
blogger.addSubscriber(mm.show);
blogger.recommend(123); //Call to publish
//Unsubscribe
blogger.removeSubscriber(mm.show);
blogger.recommend(456); //Call to publish
//Subscription of another object
user.addSubscriber(mm.show);
user.vote(789); //Call publish
jQuery version
According to the new on/off function of jQuery version 1.7, we can also define jQuery version of observers:
(function ($) {
var o = $({});
$.subscribe = function () {
o.on.apply(o, arguments);
};
$.unsubscribe = function () {
o.off.apply(o, arguments);
};
$.publish = function () {
o.trigger.apply(o, arguments);
};
} (jQuery));
The calling method is simpler than the above three versions:
//Callback function
function handle(e, a, b, c) {
// `e` is an event object, no need to pay attention
console.log(a b c);
};
//Subscribe
$.subscribe("/some/topic", handle);
//Publish
$.publish("/some/topic", ["a", "b", "c"]); // Output abc
$.unsubscribe("/some/topic", handle); // Unsubscribe
//Subscribe
$.subscribe("/some/topic", function (e, a, b, c) {
console.log(a b c);
});
$.publish("/some/topic", ["a", "b", "c"]); // Output abc
//Unsubscribe (unsubscribe uses the /some/topic name instead of the callback function, which is different from the example in version 1
$.unsubscribe("/some/topic");
As you can see, his subscription and unsubscription use string names instead of callback function names, so even if an anonymous function is passed in, we can still unsubscribe.
Summary
The use case of observers is: when changes to one object require changes to other objects at the same time, and it does not know how many objects need to be changed, you should consider using the observer pattern.
In general, what the observer pattern does is decoupling, making both parties of the coupling rely on abstraction rather than concreteness. So that changes on each side will not affect changes on the other side.