Combining Unobtrusive JavaScript with Pusher

I use Pusher to add real-time updates to my Rails application.

Here is a brief description of how Pusher works (and later I will show you what I need 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 unobtrusive JavaScript. Suppose I have an app / views / things / index.js.erb file:

$("things").update("<%= escape_javascript(render(@things))%>");  

What should I write in myChannel.bind callback to run the code above?

+3
source share
4 answers

You do not really compare apples with apples.

, XHR, things/index @thing POST things/create.

thing, Pusher - DOM.

, HTML Pusher . javascript HTML , thing DOM.


@user94154:

: .

b/c, , HTML , Pusher . :

  • HTML, " " HTML Pusher
  • , . .

div ( DOM), HTML Pusher. - :

myChannel.bind('thing-create', function(thing) {
  $("div#thing_holder").html(thing.html);
});
+1

pjax , . README Rails.

0

I understand, this is how you do it ...

Tried to write here, but indented code, etc. not working well for longer material ...

http://jbeas.com/ruby-on-rails/rails-3-pusher-app-and-unobtrusive-js/

0
source

All Articles