Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

发布订阅的实现 #7

Open
Ray1993 opened this issue Sep 18, 2017 · 0 comments
Open

发布订阅的实现 #7

Ray1993 opened this issue Sep 18, 2017 · 0 comments

Comments

@Ray1993
Copy link
Owner

Ray1993 commented Sep 18, 2017

//摘自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");
@Ray1993 Ray1993 changed the title 松散耦合 发布订阅的实现 Sep 29, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant