js设计模式中发布与订阅实现观察者模式例子

<script>

    var pubsub = {};

    (function(q) {

        var topics = {};

            subuid = -1;

        q.publish = function(topic, args) {

            if(!topics[topic]) {

                return false;

            }

            var subs = topics[topic],

                len = subs.length;

            while(len--) {

                subs[len].func(topic, args);

            }

            return this;

        }

        q.sub = function(topic, func) {

            if(!topics[topic]) {

                topics[topic] = [];

            }

            var token = ++subuid;

            topics[topic].push({

                token: token.toString(),

                func: func

            })

            return token;

        }

        q.ubsub = function(token) {

            for(var m in topics) {

                if(topics[m]){

                    for(var i=0, j=topics[m].length; i<j;i++) {

                        if(topics[m][i].token == token) {

                            topics[m].splice( i, 1 );

                            return token;

                        }

                    }

                }

            }

            return this;

        }

    })(pubsub);





</script>

<script id="test_data">

    var topic = 'test/index';

    pubsub.sub(topic, function() {alert(arguments[1])})

    pubsub.publish(topic, 2)

    pubsub.ubsub(0);

    pubsub.publish(topic, 2)

</script>

  

你可能感兴趣的:(观察者模式)