邮件发布后,Rails Action Cable向下滚动

时间:2017-06-15 08:55:53

标签: javascript jquery ruby-on-rails ruby-on-rails-5 actioncable

我配置了动作线,现在我想使用以下js功能

$('.scroll-bar').scrollTop(row);

在提交消息后向下滚动聊天

Action Cable Chat

因此,我尝试在app/assets/channels/messages.jsapp/assets/javascripts/room.js中包含以前的代码。

问题是在我执行app/assets/channels/messages.js之后,html没有,然后附加了新的<p></p>标记。

App.messages = App.cable.subscriptions.create('MessagesChannel', {  
  received: function(data) {
    $("#messages").removeClass('hidden')
    return $('#messages').append(this.renderMessage(data));
  },
  renderMessage: function(data) {
    return "<p> <b>" + data.user + ": </b>" + data.message + "</p>";
  }
});

这是我的聊天消息,我无法在仍然存在的行上运行.scrollTop(row)

我进行了测试,并在<p>之后添加了messages.js标记。

ptags

通过评论return $('#messages').append(this.renderMessage(data));的回复并在.scrollTop(row)方法之后调用,我找到了一个解决此问题的临时解决方案。该解决方案有效,但这样只会将html附加到没有<p>标记的页面中。某种程度上renderMessage无法正常工作。

我可以获取任何信息

非常感谢 Fabrizio Bertoglio

1 个答案:

答案 0 :(得分:0)

This is my temporary solution, not working correctly, because like this I will not append a <p> tag but just the text.

Basically like this the I am just appending the html without "<p> <b>" + data.user + ": </b>" + data.message + "</p>"

You can see from the picture below that the message is not inside <p> tags.

HTML Example

This is what I have done, I commented the return to execute the .scrollTop() function after $('#messages').append(this.renderMessage(data));

app/assets/channels/messages.js

App.messages = App.cable.subscriptions.create('MessagesChannel', {  
  received: function(data) {
    $("#messages").removeClass('hidden');
    $('#messages').append(this.renderMessage(data));
    height = $('.scroll-bar')[0].scrollHeight;
    $('.scroll-bar').scrollTop(height);
    /*return $('#messages').append(this.renderMessage(data));*/
  },
  renderMessage: function(data) {
    return "<p> <b>" + data.user + ": </b>" + data.message + "</p>";
  }
});

I think the solution is hear, from this post I followed to implement action cable, I don't understand who is directly calling the received: function(data) {}

is it the callback method subscribed inside messages_channel.rb?

class MessagesChannel < ApplicationCable::Channel 
    def subscribed
        stream_from 'messages'
    end 
end  

I don't have a clear idea how this callback method is calling the other method and how is the application flow.

Heroku Action Cable enter image description here