-
-
Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
# ./app/assets/javascripts/app.js.coffee | |
@App ||= {} | |
# ./app/assets/javascripts/app/view.js.coffee | |
class @App.View | |
@where: (params = { controller: null, action: null }) -> | |
controller = @_parseClassName(params.controller) | |
action = @_parseClassName(params.action) | |
try | |
new App.View[controller][action] | |
catch error | |
new this | |
@_parseClassName: (text) -> | |
text = text.replace /\W/, '.' | |
text = text.replace /(?:\b|_)([a-z])/g, ($0, $1) -> $1.toUpperCase() | |
render: -> | |
console?.log "No view found." | |
# ./app/assets/javascripts/app/view/dashboard.js.coffee | |
class @App.View.Dashboard extends @App.View | |
# ./app/assets/javascripts/app/view/dashboard/show.js.coffee | |
class @App.View.Dashboard.Show extends @App.View | |
constructor: -> | |
console?.log 'View instantiated.' | |
render: -> | |
console?.log 'View loaded.' | |
# ./app/assets/javascripts/application.js.coffee | |
$ -> | |
@view = App.View.where | |
controller: $('body').data('controller') | |
action: $('body').data('action') | |
@view.render() |
That's not a stupid idea, no. It's a simpler solution and might be good enough for most applications. Ultimately there's a threshold. If every new page the user visits makes an additional HTTP request for that page's JS, then performance may suffer. If an additional page-specific js file is needed in only a few sections of the application, then it might be more beneficial to simplify the logic and load the additional files as you've suggested.
Our js changes a lot. I wonder if, at the end of the day, the additional HTTP request wouldn't be more performant. As it stands now, a change to any JS file busts the cache on application.js
and requires the user to re-download the entire application. In this example, only changed changed would be is re-downloaded and only when the user navigates to that controller.
I don't know enough about Rails to know if this is a terrible idea or not...
What if, in
application.js
you changedrequire_tree .
torequire_directory .
so that it only compiles application level files. Then have the layout grab the controller specific JS:Stupid?