// initialize websocket
var ws = new WebSocket("ws://192.168.56.101:8080/");

console.log('starting meteorite websockets. . .');

ws.onmessage = function(msg) {
  // parse the json message
  // todo: handle non-json messages
  var json = JSON.parse(msg.data);
  
  // log the data
  console.log(json);
  
  // for each meteorite class
  $('.meteorite').each(function() {
    // if the bind keys match
    if ($(this).data('bind-key') === json.bind_key) {
      console.log('bind found');
      
      // if there is no bind-attr present, this is a collection
      if ($(this).data('bind-attr') === undefined) {
        add(json, $(this));
      // else update the element
      } else {
        update(json, $(this));
      }
      
    }
  });
}

// add an item
function add(json, $element) {
  // add to the dom
  $element.append(json.bind_data);
  // listen to subscribe events
  subscribe($(json.bind_data).find('.meteorite').data('bind-key'));  
}

// update a single attribute
function update(json, $element) {
  // get the bind data
  var bind_data = JSON.parse(json.bind_data);
  // desired attribute
  var bind_attr = $element.data('bind-attr');
  // get the attribute data
  var attr_data = bind_data[bind_attr];

  // update the property
  $element.prop('checked', attr_data);
  // update the text
  $element.text(attr_data);
  // notify event handlers that a change has occurred
  $element.trigger('change');
}

// subscribe to events when the websocket is ready
function subscribe(bind_key) {
  // set a 5ms timeout
  setTimeout(function() {
    // if the websocket is ready
    if (ws.readyState === 1) {
      // send the subscribe notice
      ws.send(JSON.stringify({ action: 'subscribe', key: bind_key }));
    // try again if not ready
    } else { subscribe(); }
  }, 5);
}

@@ -1425,36 +1425,427 @@
 %0A// 
-subscribe to events when the
+when the document is ready%0A$(document).on('page:load ready', function() %7B%0A  subscribeAfterWebsocket();%0A%7D);%0A%0A// subscribe to all bind keys of meteorite classes%0Afunction subscribeAll() %7B%0A  // for each meteorite class%0A  $('.meteorite').each(function() %7B%0A    // if there is a bind key%0A    if ($(this).data('bind-key') !== undefined) %7B%0A      // subscribe%0A      subscribe($(this).data('bind-key'));%0A    %7D%0A  %7D);%0A%7D%0A%0A// wait for
  web
@@ -1851,24 +1851,47 @@
 bsocket 
-is
+to be
  ready
+, then subscribe all
 %0Afunctio
@@ -1905,17 +1905,23 @@
 ribe
-(bind_key
+AfterWebsocket(
 ) %7B%0A
@@ -2071,77 +2071,29 @@
 tice
+s
 %0A      
-ws.send(JSON.stringify(%7B action: 'subscribe', key: bind_key %7D)
+subscribeAll(
 );%0A 
@@ -2143,16 +2143,30 @@
 ubscribe
+AfterWebsocket
 (); %7D%0A  
@@ -2170,12 +2170,195 @@
 %0A  %7D, 5);%0A%7D%0A
+%0A// subscribe to events when the websocket is ready%0Afunction subscribe(bind_key) %7B%0A  // send the subscribe notice%0A  ws.send(JSON.stringify(%7B action: 'subscribe', key: bind_key %7D));%0A%7D%0A

update subscription functions