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 hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
この順序、インデントで解決しました。
失礼しました。