hytzgroup / blog

write & read & though
0 stars 0 forks source link

publish/subscribe #19

Open hytzgroup opened 4 years ago

hytzgroup commented 4 years ago
/**
    The Publish/Subscribe pattern however uses a topic/event channel which sits between the objects wishing to receive notifications (subscribers) and the object firing the event (the publisher).
    发布订阅模式使用话题或者事件通道(系统)连接发布者和订阅者。
    This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber. 
    事件系统允许开发者自定义事件,传递自定义数据给订阅者。
    The idea here is to avoid dependencies between the subscriber and publisher.
    这样降低了发布者和订阅者的依赖关系。

 */
var pubsub = {};
(function(myObject){
    var topics = {};
    var subUid = -1;

    myObject.trigger = function(type,args){
        var listeners = topics[type],
            len = listeners ? listeners.length : 0;
        while(len--){
            listeners[len].func(type,args);
        }
        return this;
    }

    myObject.on = function(type,listener){
        if(!topics[type]){
            topics[type] = [];
        }
        var token = (++subUid).toString();
        topics[type].push({
            token:token,
            func:listener
        });
        return token;
    }

    myObject.off = function(token){
        for(m in topics){
            var listeners =  topics[m],
                listener = null;
            for(var i = 0, len = listeners.length; i < len; i++){
                listener = listeners[i];
                if(listener.token == token){
                    listeners.splice(i,1);
                    break;
                }
            }
        }
        return this;
    }

})(pubsub);

// listeners

function loginCallback(type,data){
    console.log(type,data);
}
var token = pubsub.on('loginMsg',loginCallback);
pubsub.trigger('loginMsg','this is publisher emit msg');
pubsub.off(token);