Skip to content

Instantly share code, notes, and snippets.

@kevinthompson
Created January 17, 2014 23:18
Show Gist options
  • Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
Potential Solution for Page-Specific JavaScript
# ./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()
@chantastic
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment