JS观察者模式

时间:2017-06-08 08:01:45

标签: javascript observer-pattern

我尝试观察者模式(通过这两个Urls:https://davidwalsh.name/pubsub-javascripthttp://www.dofactory.com/javascript/observer-design-pattern)但是当我调用发布函数时,侦听器数组是空的。

main.pagination.event= (function () {
    var listeners = [];   
    return {
        subscribe: function (fn) {
            listeners.push(fn);
            return {
                unsubscribe: function (fn) {
                    listeners= listeners.filter(
                        function (item) {
                            if (item !== fn) {
                                return item;
                            }
                        }
                    );
                }
            };
        },
        publish: function () {
            //it's empty
            listeners.forEach(function (item) {
                item("...");
            });
        }
    };
})();
main.pagination.init = function () {
   $('ul li').click(function () {
      main.pagination.event.publish();
   };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.listener = function (tbl) {
   alert(tbl);
};

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

它是空的,因为您在 subscribe之后调用了publish listeners数组中没有任何内容。只需改变调用的顺序

main.update.listener = function (tbl) {
    alert(tbl);
};
main.pagination.init = function () {
    $('ul li').click(function () {
        main.pagination.event.publish();
    };
};

main.update.init = function() {
    var event = main.pagination.event.subscribe(main.update.listener);
};

main.update.init(); // invoke subscribe first to add the listener to the array
main.pagination.init();