Rails+Backbone+Faye messaging, how to instantiate model and remove its element from DOM for all subscribers?

StackOverflow https://stackoverflow.com/questions/7296651

Question

I am using Rails + Backbone + Faye to make a sample chat application.

I'm currently able to use Faye's messaging capabilities to write to the DOM on a create event, though I'm not actually instantiating a backbone model. Ala Ryan Bates' tutorial I'm just calling inside of

create.js.erb

  <% broadcast "/messages/new" do %>
      $("#chats-table").append("<%= escape_javascript render :partial => "chat", :locals    => { :chat => @chat } %>");
  <% end %>

And publishing it in another javascript:

faye.subscribe("/messages/new", function(data) {
    eval(data);
});

I'd like to refactor this a bit and leverage backbone's models. A good use case would be the delete method.

My chat model is bound to a click event, delete which calls:

model.destroy();
this.remove();

Backbone will call the delete method and put a delete request to /entity/id

That also dispatches rails' /views/delete.js.erb'. In there I call a helper method which publishes a message with Ruby code.

 <% broadcast "/messages/delete" do %>
     <%= @chat.to_json.html_safe; %>
 <% end %>

listener

    var faye = new Faye.Client('http://0.0.0.0:9292/faye');
    faye.subscribe("/messages/delete", function(data) {
    }); 

Here, I was wondering if i could instantiate the deleted backbone model somehow so I could push that event onto everybody's screen and remove it from the DOM. Basically, I would like to call this.remove(); inside the faye client instead of in the chat model. Is this even possible?

Was it helpful?

Solution

Well, you should do remove on the model and let the UI listen for the event and refresh itself. Once the UI reflects the model changes you are golden.

The problem you have here is that Backbone collections/models are not an identity map. So the model object you are dealing with in the view is not the same you will instantiate and remove from the faye callback. If your messages collection is globally accessible, then I suggest you get the instance from there are remove it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top