0
Coffeescript in the Asset Pipeline
What is the Asset Pipeline?
- Part of the rails stack
- Precompiles your coffeescript/sass/haml
- Combines your coffeescript into one file
- Can be manipulated.
Example : application.coffee
#= require jquery
#= require jquery_ujs
#= require folder_name
#= require single_file
#= require_tree
Conditional file includes
- sometimes you don't want all the JS
- not just about file size
- Conflicting interests/unused code
- e.g. Admin areas
How to do it
- two config files referring to a folder
- Conditionals in the header
- Creates two seperate file trees to be parsed.
- index.coffee gets inspected within a folder
Conditional Example
<%= javascript_include_tag "application" %>
<%= javascript_include_tag "admin" if @admin %>
#admin.coffee
#= require jquery
#= require jquery_ujs
#= require admin_files
#admin_files/index.coffee
#= require_tree
Coffeescript Classes
- Coffeescript classes
- Very modular
- Can be independent using events
- Handy way to seperate concerns in JS
A Simple CS Class
class window.IPRUG.Player
constructor: (@events)->
$(@events).on 'play', @play
play: ->
$('#audio')[0].play()
Feature Detection
- Only instantiate Classes relavent to the page
- Detect features or dom elements
- Keeps minimal code running
Example
class window.IPRUG.App
constructor: ->
@player = new IPRUG.Player @ if $ '#audio'
@sockets = new IPRUG.Sockets @ if Modernizr.websockets
Namespacing
- Declare your namespace first
- Attach it to window
- Make it unique
- Assign all your CS classes to it
Advantages
- Minimal amounts of code on a page
- Easier to debug
- Allows seperation of interests
- Handy if using flash etc.
- Great for progressive enhancement.
Disadvantages
- Russian Dolls
- Potentially another http request
- Need distinct CS Classes
- Dependent on DOM structure for JS includes
Questions?