Overview:
The observer pattern is also called "Publish-subscribe" mode, and the publisher publishes the information without having to consider who the subscriber is. You do not need to notify the Publisher when you add Subscribers.
Application:
The most classic is: DOM events
In the development process we often use custom events that are also used by the observer pattern.
Scene:
Sales offices can be sent to subscribers in the text message to add the House unit price, area, volume rate and other information, subscribers receive this information can be processed separately:
varSalesoffices = {};//Define sales OfficeSalesoffices.clientlist = [];//cache list, which holds subscribers ' callback functionsSalesoffices.listen =function(FN) {//Add Subscribers This. Clientlist.push (FN);//subscribed messages are added to the cache list};salesoffices.trigger=function(){//Publish a message for(vari = 0, fn; fn = This. clientlist[i++ ]; ) {fn.apply ( This, arguments);//(2)//arguments is the parameter that was taken when the message was posted }};
Salesoffices.listen (function (price, squaremeter) {//xiaoming subscription message
Console.log (' prices = ' + price);
Console.log (' squaremeter= ' + squaremeter);
});
Ways to create values to observe objects of their own interest
varSalesoffices = {};//Define sales OfficeSalesoffices.clientlist = {};//cache list, which holds subscribers ' callback functionsSalesoffices.listen =function(Key, FN) {if(! This. Clientlist[key]) {//If you have not subscribed to such a message, create a cache list for the class message This. Clientlist[key] = []; } This. Clientlist[key].push (FN);//The subscribed message is added into the message cache list};salesoffices.trigger=function() {//Publish a message varKey = Array.prototype.shift.call (arguments),//Remove Message TypeFNS = This. Clientlist[key];//Remove the callback function collection for the message if(!fns | | fns.length = = = 0) {//If the message is not subscribed, it returns return false; } for(vari = 0, fn; fn = fns[i++];) {fn.apply ( This, arguments);//(2)//arguments is the parameter that is supplied when the message is posted}};salesoffices.listen (' SquareMeter88 ',function(Price) {//Xiao Ming subscribed to 88 square meters of house newsConsole.log (' prices = ' + price);//Output: 2000000}); Salesoffices.listen (' SquareMeter110 ',function(Price) {//Little Red Subscribe to 110 sqm House NewsConsole.log (' prices = ' + price);//Output: 3000000}); Salesoffices.trigger (' squareMeter88 ', 2000000);//published 88 sqm house priceSalesoffices.trigger (' squareMeter110 ', 3000000);//published 110 sqm house price
JS design mode (v)---observer pattern