Last active
October 13, 2017 10:23
-
-
Save itmammoth/dc6bbf73c83e5cecf8a5e7df2b7f9c2a to your computer and use it in GitHub Desktop.
A javascript function that allows you to do something on a particular page in rails application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Call the given callback function when the indicated page is loaded | |
# | |
# [Get ready] | |
# | |
# 1. Add data attributes to the body tag in your application layout file. | |
# ex) | |
# <body data-controller="<%= controller_name %>" data-action="<%= action_name %>"> | |
# | |
# 2. Put this file into app/assets/javascripts/ | |
# | |
# [Usage] | |
# | |
# onPageLoad 'posts#index', -> | |
# # Do something when controller is 'posts' and action is 'index'. | |
# | |
# onPageLoad 'posts', -> | |
# # Do something when controller is 'posts' (in any action). | |
# | |
# # Accepts multiple conditions | |
# onPageLoad ['posts#index', 'authors'], -> | |
# # Do something | |
# | |
@onPageLoad = (controller_and_actions, callback) -> | |
$(document).on 'turbolinks:load', -> | |
conditions = regularize(controller_and_actions) | |
unless conditions | |
console.error '[onPageLoad] Unexpected arguments!' | |
return | |
conditions.forEach (a_controller_and_action) -> | |
[controller, action] = a_controller_and_action.split('#') | |
callback() if isOnPage(controller, action) | |
regularize = (controller_and_actions) -> | |
if typeof(controller_and_actions) == 'string' | |
[controller_and_actions] | |
else if Object.prototype.toString.call(controller_and_actions).includes('Array') | |
controller_and_actions | |
else | |
null | |
isOnPage = (controller, action) -> | |
selector = "body[data-controller='#{controller}']" | |
selector += "[data-action='#{action}']" if action | |
$(selector).length > 0 |
$(document).on 'turbolinks:load', ->
onPageLoad 'chats', ->
pusher = new Pusher(gon.pusher_access_key, cluster: 'ap1')
この順序、インデントで解決しました。
失礼しました。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
初めまして。こちらのソース利用させていただきました。
大変参考になります。
ただ、実際にファイルなど設定を行ったのですがエラーが出ます。
ご存知あればと思い連絡させていただきました。
エラー内容
chats#indexというページにて
ソース
chats.coffee
on_page_load.coffee
基本的なところで恐縮です。
ご経験あればご教示願います。