publish_subscribe

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script>
    var mediator = (function(){
        var subscribe = function(channel,fn){
            if(!mediator.channels[channel])mediator.channels[channel] = [];
            mediator.channels[channel].push( {context: this,callback: fn} );
            return this;
        };
        var publish = function(channel){
            if(!mediator.channels[channel])return false;
            var args = Array.prototype.slice.call(arguments,null);
            for(var i= 0,l = mediator.channels[channel].length; i<l; i++){
                var subscription = mediator.channels[channel][i];
                subscription.callback.call(subscription.context,args);
            };
            return this;
        };
        return {
            channels : {},
            publish : publish,
            subscribe : subscribe,
            installTo : function(obj){
                obj.subscribe = subscribe;
                obj.publish = publish;
            }
        }
    }());

    (function(mediator){
        function initialize(){
            mediator.name = 'dudu';
            mediator.subscribe('nameChange',function(arg){
                console.log(this.name);
                this.name = arg;
                console.log(this.name);
            });
        };
        function updata(name){
            mediator.publish('nameChange','tom');
        }

        initialize();
        updata()
    })(mediator)
</script>
</body>
</html>

 

posted @ 2013-11-17 18:58  方方和圆圆  阅读(715)  评论(0编辑  收藏  举报

再过一百年, 我会在哪里?