0

I try the observer pattern (by these two Urls: https://davidwalsh.name/pubsub-javascript, http://www.dofactory.com/javascript/observer-design-pattern) but listeners array is empty when I call the publish function.

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);
};

Thanks for help.

Sándor Hatvani
  • 435
  • 1
  • 7
  • 21

1 Answers1

0

It is empty because you call subscribe after publish which does not contain anything inside the listeners array. Just change the order of the calls like so

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();
Trash Can
  • 6,608
  • 5
  • 24
  • 38
  • Thank you and sorry because my question was not enough precise. – Sándor Hatvani Jun 08 '17 at 08:21
  • Check my edit, still pretty much the same thing, just make sure your listener is defined first, then call `subscribe` to add the listener before calling `publish` – Trash Can Jun 08 '17 at 08:39
  • The listener function is on dialog A. When I click a button on dialog A it open dialog B where the observer pattern is. When the dialog B loaded dialog A subscribes the lisener (this works) and when I click a button on dialog B it fires the publish function but the listeners array is empty. I think those are in the right order. – Sándor Hatvani Jun 08 '17 at 09:28
  • Thank you for your help, it helps me. The dialog B causes my problem because when loaded it recreated the whole javascript object and deleted the old one. I put the observer pattern to dialog A and it works now. Thx. – Sándor Hatvani Jun 08 '17 at 09:41