The publish-subscribe model is also called the observer model. It defines a one-to-many relationship between objects. When an object’s state changes, all dependent objects are notified. In JavaScript development, we generally use the event model instead of the traditional publish-subscribe model.

How to implement the publish-subscribe model step by step

  1. The first step is to specify who will act as publisher. (e.g., sales offices)
  2. Then add a cached list to the publisher to hold callback functions to notify subscribers (sales office roster)
  3. When the message is finally published, the publisher iterates through the cached list, triggering the subscriber callback function stored in it in turn (iterating through the roster, sending messages one by one)

The simple implementation is as follows

var salesOffice = {} // Define the sales office
salesOffice.clientList = [] // The list of the cache, the callback function to store subscribers
salesOffice.listen = function (fn) { // Add subscribers
    this.clientList.push(fn) // Subscribed messages are added to the cache list
}
salesOffice.trigger = function () { // Publish the message
    for (var i = 0, fn; fn = this.clientList[i++];) {
        fn.apply(this.arguments)}}Copy the code

Simple test

// test
salesOffice.listen(function (prace,squareMeter) {
    console.log('Price:', prace);
    console.log('Area:', squareMeter);
})
salesOffice.trigger(2000000.110) // Price: 2000000 Area: 110

Copy the code

Has implemented in the simplest version of the release of subscription, but in fact there are problems, everyone may subscribe to a different model, the above implementation is, as long as the beginning of the sale to notify all subscriptions, obviously is not reasonable, the code to rewrite

var salesOffice = {}
salesOffice.clientList = {}
salesOffice.listen=function(key,fn){
  if(!this.clientList[key]){
    this.clientList[key]=[]
  }
  this.clientList[key].push(fn)
}
salesOffice.trigger=function(){
  arguments = Array.from(arguments)
  var key = arguments.shift()
  // var key = Array.prototype.shift.call(arguments)
  fns=this.clientList[key]
  if(! fns||fns.length===0) {return false
  }
  for(let i=0,fn; fn=fns[i++]){ fn.apply(this.arguments)
  }
 
}
 
salesOffice.listen('squarterMetter80'.function(price){
    console.log('squarterMetter80 price: '+price)
})
salesOffice.listen('squarterMetter90'.function(price){
    console.log('squarterMetter90 price: '+price)
})
 
salesOffice.trigger('squarterMeter80'.8000)
 
salesOffice.trigger('squarterMeter90'.9000)
Copy the code