Definition:
- The publish subscriber pattern is really a one-to-many dependency between objects (with message queues, the front-end code is often presented asynchronously)
- When the state of an object changes, all dependent objects are notified of the state change
- Subscriber registers the time he/she wants to Subscribe to the dispatch center. When the publisher releases the time to the dispatch center (when the event is triggered), the dispatch center schedules the time in a unified manner, and the Subscriber registers the processing code of the dispatch center.
Case study:
Implementation idea:
1. Create a class
2. Create a cache list on the class (dispatch center)
3. The on method is used to add function fn to the cache list (subscribers register events to the dispatch center).
4. The emit method retrieves the event type and executes the function in the cache list according to the event value (the publisher issues the event to the dispatch center, which processes the code).
5. The off method can unsubscribe based on the event event type
Specific code:
class Observer {
constructor(){
// Message center
this.message = {}
}
// Subscriber registration event
$on(type,fn){
// Initialize an array if it has not been registered before
if(!this.message[type]){
this.message[type] = []
}
// Push the event to the message center
this.message[type].push(fn)
}
// Delete the subscription event
$off(type,fn){
// Check whether the user is registered
if(this.message[type]) return // If not registered
// If there is only one argument
if(! fn){// Cancel registration event
this.Message[type] = undefined
}
// Remove this method
this.message[type] = this.messsage[type].filter(item= >item ! == fn) } $emit(type){// Determine whether to subscribe
if(!this.message[type]) return
// If subscribed, execute the functions in turn
this.message[type].forEach(item= > item())
}
}
// Create a function using the constructor
const person = new Observer()
// Subscribe ABC events to person
person.$on('abc',event1)
person.$on('abc',event2)
// Subscribed to aaa events
person.$on('aaa',event3)
person.$on('aaa',event4)
// ABC event1 was cancelled
person.$off('abc'Event1),/ / release
person.$emit('abc') // Print 222
1 / / events
event1(){
console.log('1111')}2 / / events
event2(){
console.log('2222')}3 / / events
event3(){
console.log('333')}4 / / events
event4(){
console.log('444')}Copy the code