Home >Web Front-end >JS Tutorial >Detailed explanation of javascript publish-subscribe model (with examples)

Detailed explanation of javascript publish-subscribe model (with examples)

不言
不言forward
2018-10-26 15:39:003507browse

This article brings you a detailed explanation of the JavaScript publish-subscribe model (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Publish and subscribe model

The event publish/subscribe model (PubSub) helps us achieve looser decoupling in asynchronous programming, even in MVC and MVVC architectures And the design pattern is also indispensable for the participation of the publish-subscribe model.

Advantages: Achieve deeper decoupling in asynchronous programming

Disadvantages: If you use the publish-subscribe model too much, it will increase the difficulty of maintenance

Implement publishing Subscription mode

var Event = function() {
    this.obj = {}
}

Event.prototype.on = function(eventType,fn) {
    if(!this.obj[eventType]) {
        this.obj[eventType] = []
    }
    this.obj[eventType].push(fn)
}

Event.prototype.emit = function() {
    // 取第一个参数,作为eventType
    var eventType = Array.prototype.shift.call(arguments);
    //  获取事件数组
    var arr = this.obj[eventType];
    var len = arr.length;
    // 循环数组,一次执行其中的函数
    for(var i=0;i<len var ev.on ev.emit><p>The above code can only implement subscription first and then publish. If you publish it directly, an error will be reported. How can I publish first and then subscribe? </p>
<pre class="brush:php;toolbar:false">var Event = function() {
    this.obj = {};
    this.cacheList = [];
}

Event.prototype.emit = function() {
    const args = arguments;  //函数参数
    const that = this;  //this指向,保持cache函数的this指向
    function cache() {
        var eventType = Array.prototype.shift.call(arg)
        var arr = that.obj[eventType]
        for (let i = 0; i <p>After changing it to this, the process of publishing the function first and then subscribing is realized. But you can only publish first and then subscribe, not the other way around. </p><p class="comments-box-content"></p>

The above is the detailed content of Detailed explanation of javascript publish-subscribe model (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:github.io. If there is any infringement, please contact admin@php.cn delete