This is the 9th day of my participation in Gwen Challenge
define
The publisk-subscribe pattern, also known as the observer pattern, defines a one-to-many dependency between objects. When an object’s state changes, all dependent objects are notified. In javascript development, the event model is often used instead of the traditional publish-subscribe model. One undesirable side effect of splitting a system into a series of cooperating classes is the need to maintain consistency between corresponding objects, which can make maintenance, extension, and reuse difficult. Subscription publishing is used when changes to one object require changes to other objects, and it does not know exactly how many objects need to be changed. When an abstract model has two aspects, one of which depends on the other, the subscription publishing pattern encapsulates the two in separate objects, allowing them to change and reuse independently of each other. What the subscription publishing model does is decouple. Make both sides of the coupling dependent on abstraction, rather than concrete, so that changes on either side do not affect changes on the other.
We can implement simple on and emit methods. The code is as follows:
Class Event {constructor(){this.obj = {}} // The function takes two arguments, the Event name, and the function after the Event is fired. The SUBSCRIBE function stores the supplied function into the corresponding event array. this.on = (name,fn)=>{ if(! this.obj[name]){ this.obj[name] = []; } this.obj[name].push(fn); } this.emit = (name,val)=>{if(this.obj[name]){this.obj[name].map((fn)=>{fn(val); }); }} // The module can also unsubscribe. The function takes two arguments, the name of the unsubscribed event, and the corresponding function. If no function is passed, all functions corresponding to the event are cleared by default. this.off = (name,fn)=>{ if(this.obj[name]){ if(fn){ let index = this.obj[name].indexOf(fn); if(index > -1){ this.obj[name].splice(index,1); } }else{ this.obj[name].length = 0; // set the length to 0 rather than obj[name] = [], because if the array is empty, a new space is created, and if the array is 0, there is no need to create a new space}}}}Copy the code