Last Updated: February 25, 2016
·
633
· geetotes

99 router params on the wall, 99 router params, take one down, pass it around, 98 router params, etc. etc.

So let's say you're developing an application that is using backbone router params to guide requests to your RESTful backend. For example, you've developed a single-page backbone app that shows the number of girls or number of boys in a particular state*.

Your router may look something like this (in coffeescript)

class MyApp.Routers.GenderedStates extends Backbone.Router
  routes: 
     "query/:gender/:state" : "doLookup"

And your API backend takes a request like this**:
GET /query/boys/ny.json #return the number of boys in NY state

So your doLookup function in the router is first going to have to take those params

doLookup: (gender, state) ->

And pass them onto the view

@appView ||= new MyApp.Views.GenderState({
  el: $('#app')
  gender: gender
  state: state
})
@appView.render()

So, now, in your view layer:

class MyApp.Views.GenderState extends Backbone.View

We can grab the gender and state variables. Now notice they are not attached to the this object (like @el) is. Instead they live in the options object.

#still in the view layer
initialize: =>
GenderCount = MyApp.Collections.GenderCount({
  gender: @options.gender
  state: @options.state
})

Ok, cool. With the @options object, you can access those params you added when you created the view. Now, to access the params in the Collection, you'll need to add some code to the initializer.

class MyApp.Collections.GenderCount extends Backbone.Collection
intialize: (options) => #oh hai options object!
  @gender = options.gender
  @state = options.state

Cool! Now your collection is storing the value of the options you passed in when you created it, and they are accessible throughout the whole object.

Now the whole point of this exercise was to be able to dynamically assign a url to the collection based on stuff in the router. Note how this doesn't work:

#still in the collection layer
url:  '/query/' + @gender + '/' +@state + '.json'

This is because this.gender must be evaluated! The trick is to make the url a function that returns a string:

url: ->
  '/query/' + @gender + '/' +@state + '.json'

And that is how you can assign random, arbitrary parameters to basically any Backbone object. Note how in this example, the parameters haven't been random or arbitrary, but basically variables from the router have been copied throughout the entire stack (Router, View, Collection)

And now you can sing the song that's the title of the post!

*Of course, if you're writing an application that assigns people into binary gender roles, you're doing it wrong.

**Why not just have the backend return the numbers for all the states and deal with the selection in the app's collectio--QUIET! The point of this example is to show how to pass variables from the router across the application.