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 JavaSc开发者_StackOverflow社区ript. 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?
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:
- If it isn't much HTML markup, you might want to break the "Don't Repeat Yourself" rule and repeat the HTML markup in your controller and send that to Pusher
- If it is a lot of markup, I would abstract my view generation code to helpers. You can call a helper from your controller, too.
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);
});
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.
pjax might be what you are looking for. Included in the README is how to get started with it in Rails.
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/
精彩评论