Most of the code for the ActionCable setup in my Rails app is in a file that only seems to load when I am visiting the page that is named after the resource. In this case, scroll_bottom()
runs when I am on the messages #index
, but throws an error in console when I am anywhere else.
I can tell that this has something to do with $(document).on 'turbolinks:load', ->
. How can I exclude scroll_bottom()
when I am not on the #index
page?
messages.coffee
App.messages = App.cable.subscriptions.create "MessagesChannel",
connected: ->
console.log 'Connected'
disconnected: ->
console.log 'Disconnected'
received: (data) ->
alert data["mmmm"]
peak: (message, conversation_id) ->
@perform 'speak', message: message, conversation_id: conversation_id
$(document).on 'turbolinks:load', ->
submit_message()
scroll_bottom()
submit_message = () ->
$('#response').on 'keydown', (event) ->
if event.keyCode is 13
message = event.target.value
conversation_id = $("#messages").data("conversation-id")
App.messages.speak(message, conversation_id)
event.target.value = ""
event.preventDefault()
scroll_bottom = () ->
$('#messages').scrollTop($('#messages')[0].scrollHeight)
scroll_bottom = () ->
$('#messages').scrollTop($('#messages')[0].scrollHeight)
Change this function to:
scroll_bottom = () => {
const el = $('#messages').scrollTop($('#messages')[0]
if (el) {
return el.scrollHeight;
}
}
That way if el is not defined no error will be thrown
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.