Created
September 29, 2012 15:57
-
-
Save house9/3804446 to your computer and use it in GitHub Desktop.
rails asset pipeline - auto invoke javascript based on controller / action
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
<!-- | |
1) include in layout files after all other javascript includes | |
2) if you have coffeescript classes that match your controller name - they will be invoked automatically | |
WARNING: as a general rule don't write js like this with ruby mixed in, | |
this is one of those rare cases where it 'works' well | |
--> | |
<script> | |
$(document).ready(function () { | |
var o; | |
if (window.APP) { | |
if (window.APP.<%= controller_name.classify %>) { | |
o = new window.APP.<%= controller_name.classify %>(); | |
if (o.<%= action_name %>) { | |
o.<%= action_name %>(); | |
} else { | |
log("NO: window.APP.<%= controller_name.classify %>.<%= action_name %>"); | |
} | |
} else { | |
log("NO: window.APP.<%= controller_name.classify %>"); | |
} | |
} | |
else { | |
log("NO: window.APP"); | |
} | |
}); | |
</script> |
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
# CoffeeScript class maps to controller, methods map to actions | |
class User | |
new: -> | |
@bindForNewUserForm() | |
create: -> | |
@bindForNewUserForm() # incase of server side validation rendering new view in create action | |
profile: -> | |
# call other re-usable js 'component' | |
new window.APP.Users.Profile().run() | |
# bind objects to APP namespace | |
window.APP ?= {} | |
window.APP.User = User |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment