Publish subscribe model concept

Publish and subscribe model: Subscriber registers the event they want to Subscribe to the dispatch center. When Publisher publishes the event to the dispatch center, that is, when the event is triggered, The processing code registered with the dispatch center by the Fire Event subscriber.

There are three main actors: subscriber, dispatch center and publisher

Publish subscribe pattern instances

/** * Publish-subscribe */
// Define a press release platform
// the main functions include the informationWarehouse, subscribe, and release tasks.
let task = {
    informationWarehouse: {},
    subscribe(key, fn) {
        if (typeof this.informationWarehouse[key] === "undefined") {
            this.informationWarehouse[key] = []
        }
        this.informationWarehouse[key].push(fn) // Subscribed messages are pushed to the dispatch center
    },
    release(type, news) {
        let fns = this.informationWarehouse[type]
        // If the dispatch center does not have this resource, return end
        if (typeof fns === "undefined" || fns.length === 0) return;
        fns.forEach(fn= >{ fn(news); }}})console.log("Subscription -- -- -- -- -- -- -- -- -- -");
// Subscribe to entertainment headlines
task.subscribe('entertainment'.val= > {
    console.log('Entertainment Headlines from Xiao Wang's subscription'.JSON.stringify(val))
})
// Subscribe to tech headlines
task.subscribe('technology'.val= > {
    console.log('Tech headlines xiao Liu subscribes to'.JSON.stringify(val))
})
// Subscribe to history headlines
task.subscribe('history'.val= > {
    console.log('Historical headlines that Xiao Li subscribed to'.JSON.stringify(val))
})
/** * system push headlines */
console.log(Released "-- -- -- -- -- -- -- -- -- --");
task.release('entertainment', {
    title: "The implication of brother Overcoat giving his daughter-in-law a red envelope.".url: "https://www.toutiao.com/a6966769740203262478"
})
task.release('technology', {
    title: "The release of segment 192 is approaching China's 5G broadcasting.".url: "https://www.toutiao.com/a6966480940277334535"
})
task.release('history', {
    title: "Who are Yuan Longping's parents?.url: "https://www.toutiao.com/a6966099280075424267"
})
console.log("Dispatch Center", task.informationWarehouse);
Copy the code