Skip to content

Instantly share code, notes, and snippets.

@IvanTorresEdge
Created October 2, 2012 15:23
Show Gist options
  • Select an option

  • Save IvanTorresEdge/3820086 to your computer and use it in GitHub Desktop.

Select an option

Save IvanTorresEdge/3820086 to your computer and use it in GitHub Desktop.
Generate URL helper methods for Backbone router
# generates URL functions for each of the routes
#
# #### Example:
#
# Given the following routes
#
# routes:
# '/posts/:id' : 'showPost'
# '/posts/:id/comments' : 'comments'
#
# this function will generate the functions `showPostUrl` and `commentsUrl`:
#
# showPostUrl(1)
# # => /posts/1
#
# commentsUrl(1)
# # => /posts/1/comments
#
_generateUrls: () ->
# for each route
for route, name of @routes
# generate the corresponding URL function
@["#{name}Url"] = ((route) ->
return ->
args = arguments # arguments passed to the Url function
index = 0 # argument index
param = /[:\*]\w+/g # regexp for route fragment parameters
# replaces each of the parameters in the route fragment
route.replace param, -> args[index++]
)(route)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment