WebSocket消息回调和Knockout JS视图模型通信

时间:2017-05-26 12:15:14

标签: knockout.js knockout-3.0 knockout-postbox

我需要将WebSocket连接的“onmessage”回调函数中的数据提供给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

        }

    };

但问题是,我没有在我的代码中创建ViewModel的实例。我正在使用KnockoutJS的自定义组件并通过以下代码注册它

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

我的组件的视图模型如下

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

1 个答案:

答案 0 :(得分:1)

将本地observable或viewmodel传递给自定义组件

并更新socket事件的本地observable(将更新组件)

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