Maximus S
Maximus S

Reputation: 11115

Unobstrusive javascript ajax code in Rails

create.js.erb

    $("#chat").append("<%= j render(@message) %>");
    $("#new_message")[0].reset();

I need to change this to something similar to the below:

function newMessage() {
    $("#chat").append("<%= j render(@message) %>");
    $("#new_message")[0].reset();
}
channel.bind('new_message', newMessage());

This is my ajax request call for my create method in MessagesController. I need to change like that to call this function as a callback from index.html.erb to use the Pusher server. What I want to achieve is a real-time chat application, so all clients should be abled to pushed a message without refreshing the browser.

index.html.erb

<script src="http://js.pusherapp.com/1.9/pusher.min.js"></script>
<script type="text/javascript" charset="utf-8">
  $(function() {
    var pusher = new Pusher('app_key'); // Replace with your app key
    var channel = pusher.subscribe('my_channel_chat');
  });
</script>

I think I am somehow confused with the context in create.js.erb file. Could anyone help me with this?

Update:

MessagesController

  def index
    @messages = Message.all
  end

  def create
    @message = current_user.messages.create!(params[:message])
    Pusher.trigger('my_channel_chat', 'new_message', {:message => @message.content})
  end

Upvotes: 0

Views: 116

Answers (1)

vee
vee

Reputation: 38645

I'm not sure if I fully understand your questions but based on what I understand this should solve your problem:

function newMessage() {
    $("#new_message")[0].reset();
}
$('#chat').on('new_message', newMessage);
$("#chat").append("<%= j render(@message) %>").trigger('new_message');

Upvotes: 1

Related Questions