1. Publish-Subscribe mode is also called the Observer pattern, which defines a one-to-many dependency between objects.
2. How to implement the Publish-subscribe mode
2-1. First specify a good publisher
2-2, add a buffer list to the publisher, the user holds the callback function to inform the Subscriber
2-3. When the last message is published, the Publisher will traverse the cache list and trigger the subscriber callback function
Example:
var salesOffice = {};
Salesoffice.clientlist = [];
Salesoffice.listen = function (KEY,FN) {
if (!this.clientlist[key]) {
This.clientlist[key] = [];
}
This.clientlist[key].push (FN);
}
Salesoffice.trigger = function () {
var key = Array.prototype.shift.call (arguments),
FNS = This.clientlist[key];
if (!fns | | fns.length = = 0) {
return false;
}
for (var i=0,fn; fn = fns[i++];) {
Fn.apply (this,arguments);
}
}
Salesoffice.listen (' S88 ', function (p) {
Console.log ("Price +" + p)
})
Salesoffice.listen (' s300 ', function (p) {
Console.log ("Price +" + p)
})
Salesoffice.trigger (' S88 ', 20000);
Salesoffice.trigger (' s300 ', 3000);
Common implementations of publish subscriptions:
Learn the Publish-subscribe (Viewer) mode of JavaScript design patterns