Publish and Subscribe Mode
PubSub helps us to decouple more loosely in asynchronous programming, even in MVC and MVVC architectures and design patterns.
Advantages: Deeper decoupling in asynchronous programming
Disadvantage: Overuse of Publish-Subscribe mode increases maintenance difficulty
Implementing a Publish-Subscribe Model
var Event = function() { this.obj = {} } Event.prototype.on = function(eventType,fn){ if(!this.obj[eventType]) { this.obj[eventType]=[] } this.obj[eventType].push(fn) //This way the method function is put in. } Event.prototype.emit =function() { var eventType = Array.prototype.shift.call(arguments) var arr = this.obj[eventType] //The method function is taken out here. for(let i =0;i<arr.length; i++){ arr[i].apply(arr[i],arguments) //Print out the functions in emit's value assignment on } } var ev = new Event() ev.on('click',function(a){ //Subscription function console.log(a) //5 }) ev.emit('click',5)
Must subscription function logic take precedence over publishing function
Consider the following scenarios:
$.ajax('', () => { // Asynchronous subscription function logic }) // When the publishing function is executed elsewhere, there is no guarantee that the subscription function is executed when the publishing function is executed.
So that's what we should do.
var Event = function () { this.obj = {} this.cacheList = [] } Event.prototype.on = function (eventType, fn) { if (!this.obj[eventType]) { this.obj[eventType] = [] } this.obj[eventType].push(fn) for (let i = 0; i < this.cacheList.length; i++) { this.cacheList[i]() //on triggers functions stored in cacheList } } Event.prototype.emit = function () { var arg = arguments var that = this function cache() { var eventType = Array.prototype.shift.call(arg) var arr = that.obj[eventType] for (let i = 0; i < arr.length; i++) { arr[i].apply(arr[i], arg) } } this.cacheList.push(cache) //The emit triggered function is saved in the cacheList //Deliver to on to trigger, so that the publishing function is executed before the subscription function } var ev = new Event() ev.emit('click', 5) //The premise of this use is that subscriptions must be triggered first. //Then wait for the cacheList[i]() method in the publishing function to execute ev.on('click', function (a) { console.log(a) })