Reputation: 16574
I'm using Pusher to add real-time page updates to my Rails app.
Here's a brief synopsis of how Pusher works (and later I'll show you what I'd like it to do):
Controller:
class ThingsController < ApplicationController
def create
@thing = Thing.new(params[:thing])
if @thing.save
Pusher['things'].trigger('thing-create', @thing.attributes)
end
end
end
Javascript (in <head>...</head>
):
var pusher = new Pusher('API_KEY');
var myChannel = pusher.subscribe('MY_CHANNEL');
myChannel.bind('thing-create', function(thing) {
alert('A thing was created: ' + thing.name); // I want to replace this line
});
I want to replace the commented line with an ajax request to trigger some unobtrusive JavaScript. Assume I have the file app/views/things/index.js.erb:
$("things").update("<%= escape_javascript(render(@things))%>");
What should I write in the myChannel.bind callback to trigger the above code to execute?
Upvotes: 3
Views: 566
Reputation: 926
I understand, here is how you do it...
Tried writing it on here but the code indenting, etc doesn't work well for longer stuff...
http://jbeas.com/ruby-on-rails/rails-3-pusher-app-and-unobtrusive-js/
Upvotes: 0
Reputation: 18572
You are not really comparing apples-to-apples here.
You are comparing the template rendered in an XHR request to things/index
to the attributes of the @thing
object from a POST to things/create
.
You need to process the thing
object that gets returned from Pusher in the web browser and modify the DOM accordingly.
Or, an easier solution would probably be to have your controller send formatted HTML to Pusher instead of object attributes. Then your javascript code could just insert the formatted HTML instead of trying to parse the thing
object and modify the DOM manually.
Response to @user94154's comment:
DISCLAIMER: I never heard of Pusher until your question.
This does create a challenge b/c typically your HTML is formatted in the view, but you have to send data to Pusher from the controller. I can think of a few ways to do this:
On the client side, you should have an empty div (or some DOM element) that can hold the HTML from Pusher. And do something like this:
myChannel.bind('thing-create', function(thing) {
$("div#thing_holder").html(thing.html);
});
Upvotes: 1
Reputation: 16341
pjax might be what you are looking for. Included in the README is how to get started with it in Rails.
Upvotes: 0
Reputation: 746
http://blog.new-bamboo.co.uk/2010/5/12/integrating-pusher-into-a-complex-app-in-one-day
A little over my head, but I think it may put you on the right track.
Upvotes: 0