Search code examples
javascriptruby-on-railsactioncable

How to easily send DOM elements for ActionCable?


I'm not sure if I'm just trying to do something crazy here, maybe I just need pointing in the right direction. I have a list of elements, with tick boxes. I need two people to know (interview situation) if the other has ticked a box. ActionCable seemed perfect for this.

Everything is set up, actioncable-wise, but I need to send the exact element that needs to be ticked to actioncable so that it can tick it on the other person's front-end. I have tried to send the DOM element but it gets serialised into JSON and I can't change it back on the other end (or simply don't know how to use it).

Below is my code so far. The first box.html is to tick your own box on the form. Then after the first preventDefault() I try to send the same box element to actioncable to tick it on the other person's front-end.

  $('.btn-group-vertical').each(function(){
    var $this = $(this);
    var success = $this.find('.applicant-success')
    var failure = $this.find('.applicant-failure')
    var box = $this.parent().next().find('.int_success');
    success.on('click', function(e) {
      box.html("<img class='interview-img3' src='/images/tick.png'>");
      e.preventDefault();
      App.room.ping(box);
    });
});

Solution

  • DOM elements are local to page document on one side of connection. You need to introduce some unique id, that will be valid across all involved systems. It may be id from corresponding database record, some natural key, or even SecureRandom.hex (but in this case you'll have to ensure that both involved users will get same ids)

    For example: <div class='int_success' data-id='<%= applicant.id %>'>

    And App.room.ping(box.data('id'))