Amit Dube
Amit Dube

Reputation: 1027

WebSocket Message Callback and Knockout JS View Model Communication

I need to make data which is available in the "onmessage" Callback function of WebSocket connection to a Component View Model of KnockoutJS.

sockjs.onmessage = function (e) {
        //console.log('[.] message', e.data);
        if(e.data && e.data.length){
            var jsonData = JSON.parse(e.data);

            //I need to make this jsonData available to Custom Component of knockoutJS

        }

    };

But the problem here is, I am not creating the instance of ViewModel in my code. I am using Custom Components of KnockoutJS and registering it through the below code

ko.components.register('bing-map', {
        viewModel: { require: 'bing-maps/bing-maps' },
        template: { require: 'text!bing-map/bing-map.html' }
    });

My Component's View Model is as below

define(['knockout'], function(ko){
var MapViewModel = function(params){
    var self = this;
    self.map = {
        options:{
            credentials:<bing map key>
        }
    }
}
return MapViewModel;
});

Upvotes: 0

Views: 217

Answers (1)

Ja9ad335h
Ja9ad335h

Reputation: 5075

pass a local observable or viewmodel to custom component

and update local observable on socket event (which will update component)

ko.components.register('bing-map', {
  viewModel: MapViewModel,
  template: '<div data-bind="foreach: data"><div data-bind="text: $data"></div></div>'
});


function MapViewModel(params) {
  var self = this;
  self.map = {
    options: {
      credentials: params.other
    }
  };
  debugger;
  self.data = params.data;
}

// it could a ViewModel or just a global observable
var dynamicData = ko.observableArray([Number(new Date())]);
ko.applyBindings();


// socket.io simulation
var timer = 0;
var si = setInterval(function() {
  dynamicData.push(Number(new Date()));
  timer++;
  // clear after 10 intervals
  if(timer > 9) clearInterval(si);
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<bing-map params="data: dynamicData, other: 123"></bing-map>

Upvotes: 1

Related Questions