Skip to content

Instantly share code, notes, and snippets.

@ChunAllen
Created August 15, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChunAllen/05c9d9318c9bee04e82c6049ce6527c0 to your computer and use it in GitHub Desktop.
Save ChunAllen/05c9d9318c9bee04e82c6049ce6527c0 to your computer and use it in GitHub Desktop.
Calling Javascript per controller and its action
doctype html
html
head
meta charset='UTF-8'
meta name='viewport' content='width=device-width, initial-scale=1.0'
meta http-equiv='x-ua-compatible' content='ie=edge'
title APP_NAME
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
- controller.js_assets.each do |name|
= javascript_include_tag name, 'data-turbolinks-track' => true
= csrf_meta_tags
body data=body_data class=body_css_class
//= require ./controllers/base
def body_data
data = { view: "#{controller_path}##{action_name}" }
data[:debug] = 'true' if Rails.env.development?
data
end
def body_css_class
controller_name = controller_path.underscore.tr('/', '-')
"#{controller_name} #{controller_name}-#{css_action_name}"
end
# app/controllers/base.js.coffee
window.Controllers = {} # namespace for controller loaders
controllers = {} # holds the loaded controllers for re-use when working with Turbolinks
debug = undefined
# helper to bind an event handler and optionally call it immediately
Controllers.bind = (call, $el, selector, evt, handler) ->
if call
for dt in $el
for ct in $(dt).find(selector)
handler({ currentTarget: ct, delegateTarget: dt })
$el.on(evt, selector, handler)
return
r
# run the controller-action for the current view
$(document).on 'ready page:load', ->
$body = $(document.body)
debug = $body.attr('data-debug')
run($body.attr('data-view'))
return
run = (view) ->
console.log('view:', view) if debug
return if !view
[controller, action] = view.split('#')
if (loader = Controllers[controller])
c = (controllers[controller] ||= new (loader()))
return if c.before_action && c.before_action(action) == false
return if c[action] && c[action](action) == false
return if c.after_action && c.after_action(action) == false
return
# app/controllers/admin/base_controller.rb
class Admin::BaseController < ApplicationController
JS_ASSETS = %W( application users ).freeze
end
#app/controllers/admin/users.js.coffee
Controllers['admin/users'] = -> class AdminUsers
index: (action) ->
...
new: (action) ->
...
create: (action) ->
...
edit: (action) ->
...
update: (action) ->
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment