I saw a few posts referencing a similar issue, but not quite the same thing.
Here is a snippet from the top of my routes file.
I’m wondering if the approach I’m using works to call global events on each of the routes. The events I’m using are pretty standard, simple events like clearing the #items container.
As you can see, I’m calling on the “all” event in the constructor, and then pointing to several methods defined in the routes file.
My question is, say I want the same global event on several screens; say, all of the “catalog” screens. I’ve been doing some strange and admittedly hacky tricks to get the ou
@routeName = route.split(":")[1]
# only substantiate the dropdown on User Catalog screen.
if @routeName is "catalogScreen" or @routeName is "catalogPDFScreen"
As I’m sure you can imagine, this is not ideal, nor is it particularly clean. I’m just trying to find ways to DRY up my router file to catch all of these global events, and this was the best I could think of.
routes:
"" : "homeScreen"
"catalogs" : "catalogsScreen"
"catalogs/:id" : "catalogScreen"
"catalogs/:id/page/:page_id" : "catalogScreen"
"catalogs/:id/pdf" : "catalogPDFScreen"
"catalogs/:id/pdf/page/:page_id" : "catalogPDFScreen"
"catalogs/:id/category/:category_id" : "categoryScreen"
"departments/:id" : "departmentScreen"
"notifications" : "notificationsScreen"
"settings" : "settingsScreen"
"products/:id" : "productScreen"
"catalog/:catalog_id/search/:search_query": "searchCatalogScreen"
"search/:search_query" : "searchScreen"
"login" : "loginScreen"
"members/:member_id/catalogs/:catalog_id" : "userCatalogScreen"
"members/:member_id" : "profileScreen"
":user_name/:catalog_name" : ""
#extends router class to allow storing of routes for a history
constructor: (options) ->
@on "all", @storeRoute
@on "all", @clearAlerts
@on "all", @clearScroll
@on "all", @setSearch
@on "all", @setNav
Thanks in advance for anyone’s help on this! I’m growing more and more experienced with Backbone but I obviously have some stuff to learn.
In terms of DRY-ness in the route table itself, you can utilize the support for optional router parameters to combine the routes that share the same root, but different parameters:
As for attaching common actions to some routes, but not all, there are a number of options. I think the cleanest way would be to split your router into multiple routers:
CatalogRouterfor thecatalogs*urls, etc. This only makes sense if the routers would map naturally to your application structure.If you don’t want to split your routers, another way would be to trigger a custom event for the routes
And elsewhere:
Or if your event handlers don’t need the route arguments, you can use underscore’s
composefor some syntactic sugar.