Skip to content

发布订阅的实现 #7

Description

@Ray1993

//摘自alloyTeam团队的曾探·著

var imitate = (function() {
    var imitate = {
        clientList: [],
        listen: function(key, fn) {
            if (!this.clientList[key]) {
                this.clientList[key] = [];
            }
            this.clientList[key].push(fn);
        },
        trigger: function() {
            var key = [].shift.call(arguments);
            var fns = this.clientList[key];

            // 如果没有对应的绑定消息
            if (!fns || fns.length === 0) {
                return false;
            }

            for (var i = 0, fn; fn = fns[i++];) {
                // arguments 是 trigger带上的参数
                fn.apply(this, arguments);
            }
        }
    }
    return function() {
       return Object.create(imitate);
    }
})();
var eventModel = imitate();  //得到上面的对象
eventModel.listen("jimmy",function(){console.log("jimmy");});  //jimmy
eventModel.trigger("jimmy");

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions