Search code examples
javascriptknockout.jspubnub

Why is my knockout module losing it's binding when receiving a PubNub message?


In a knockout module, I have an observable array that is iterated in the view using a foreach:

    <div id="data" data-bind="foreach: dataItems, visible: !loading()">
      <!-- ko compose: {model: $data} --><!-- /ko -->
    </div>

I have a function to fill this observable array, this way:

    var dataItems = ko.observableArray();
    var getItems = function(isAMessage){
        dataItems([]);
        dataItems.push(new dataItem('1'));
        dataItems.push(new dataItem('2'));
        dataItems.push(new dataItem('3'));

        if (isAMessage) {
            dataItems.push(new dataItem('4'));
            dataItems.push(new dataItem('5'));
            dataItems.push(new dataItem('6'));
        }
    }

And in the activate funcion of the module, I'm subscribing to a pubnub channel, this way:

    var activate = function () {
        getItems(false);

        var pubnub = PUBNUB.init({
            publish_key: 'pub-...',
            subscribe_key: 'sub-...'
        });

        pubnub.subscribe({
            channel: 'someChannel',
            message: function (m) {
                getItems(true);
            }
        });
    };

The thing is that when I receive a pubnub message, the function gets called but the observable array dataItems has no subscriptors, so, the view is not updated. When the function getItems is called from the activate function, dataItems has 2 subscriptors, but when it's called from the pubnub message callback, it has none. I don't know what am I doing wrong!!!


Solution

  • I found the problem, I wasn't injecting pubnub into the module.