码迷,mamicode.com
首页 > Web开发 > 详细

观察者模式 与 jQuery.Callbacks

时间:2015-03-03 13:13:09      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

var Subscriber = function(){
    var subName = arguments[0];
    return function(){
        console.log("我是"+subName,"我收到了"+arguments[0]);
    }
};


var XM = Subscriber("小明");
var XA = Subscriber("小暗");


var pub_sub = function(){
    var subList = [];
    var pub = {
        add:function(){
            subList.push(arguments[0]);
        },
        remove:function(){
            for(var i=0;i<subList.length;i++){
                if(arguments[0] == subList[i]){
                    subList.splice(i,1);
                    i--;
                }
            }
        },
        send:function(){
            for(var i=0;i<subList.length;i++){
                (subList[i])(arguments[0]);
            }
            if(i == 0){console.log("我是小明和小暗他爹,他们都失联了")}
            console.log("--------------------------")
        }
    };
    return pub;
};

var Publisher = pub_sub();

Publisher.add(XM);
Publisher.add(XA);
Publisher.send("第一条消息");

Publisher.remove(XM);
Publisher.send("第二条消息");

Publisher.add(XM);
Publisher.send("第三条消息");

Publisher.remove(XA);
Publisher.send("第四条消息");

Publisher.add(XM);
Publisher.send("第五条消息");

Publisher.remove(XM);
Publisher.send("第六条消息");

 

观察者模式 与 jQuery.Callbacks

标签:

原文地址:http://www.cnblogs.com/get-rabbits/p/4310542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!