JavaScript Observer Pattern

var Users = {
    list: [],
    listeners: {},
    add: function(name) {
        this.list.push({name: name});
        this.dispatch("user-added");
    },
    on: function(eventName, listener) {
        if(!this.listeners[eventName]) this.listeners[eventName] = [];
        this.listeners[eventName].push(listener);
    },
    dispatch: function(eventName) {
        if(this.listeners[eventName]) {
            for(var i=0; i<this.listeners[eventName].length; i++) {
                this.listeners[eventName][i](this);
            }
        }
    },
    numOfAddedUsers: function() {
        return this.list.length;
    }
}

Users.on("user-added", function(obj) {
    alert(Users.numOfAddedUsers());
    console.log("obj:",obj);
});

Users.add("Krasimir");
Users.add("Tsonev");

 

Referring to http://jsfiddle.net/krasimir/sHNKD/3/

posted @ 2016-04-27 23:16  wsion  阅读(228)  评论(0编辑  收藏  举报