Jamie Mclaughlan
Jamie Mclaughlan

Reputation: 875

Knockout Postbox communicating between components - how to ensure subscriber is active

I have an issue where I am publishing on a knockout observable within a component, and have another component with a view model that subscribes to this postbox event.

The publish event is within my 'data-table' components view model and is as follows:

this.pagerParams = ko.observable({ currentPage: this.currentPage, totalItems: this.recordsTotal, itemsPerPage: this.length }).publishOn("pagerParams");

I then have a 'pager' component which subscribes to this postbox publish.

ko.postbox.subscribe("pagerParams", (params: PagerParams) => {
            this.assignParamValues(params, false);

            this.numberOfPages(Math.ceil(this.totalItems() / this.itemsPerPage()) || 1);
            this.pageNumbers(this.getPageNumbers());
        });

The above postbox subscription is registered in the view models constructor. Depending on which component becomes active first, I sometimes get an issue where the pagerParams subscription is published in the 'data-table' components view model, but the pager does not acknowledge that the event has been published whatsoever.

I've found that the reason for this is because the 'pager' component needs to become active before the 'data-table' component, otherwise the 'pager' view models subscription only checks for any incoming publishes when that line of code has been run.. and a lot of the time, this is after the data-table has published the event.

My question is, how can I ensure that the pager component becomes active before the data-table component so that the pub-sub event system works in this as expected in this scenario?

Upvotes: 0

Views: 474

Answers (1)

Roy J
Roy J

Reputation: 43899

You need a handshake protocol. Each component will publish a started message on the postbox upon startup. Each will also subscribe to the started message from the other and upon receiving it, will issue started again and unsubscribe.

Whichever starts first will publish a message that is never received. The 2nd to start will publish, the 1st will receive that, re-send, and unsubscribe, and the 2nd will re-send a message that is never received. Each knows that the other is alive, and can do any dependent tasks then.

Upvotes: 1

Related Questions