When and why would I use Backbone.js Router for routing instead of routing via server-side code? Could someone elaborate on that since it's my first time exposed to do routing on client-side.
You've presented a false dichotomy. The reality is that there is probably never going to be a situation when you'll use Backbone's router in place of a server-side solution. That said, there is certainly a growing trend toward using client-side routers in general (not specifically Backbone's) to create one-page apps—e.g., Ember.js. Here are your options:
This is the classic approach that is a big component of frameworks like Rails. It is a mature strategy that draws very bright lines between your models, views, and controllers. It's certainly not going away anytime soon, and for good reason: it's great if you're not developing a one-page app, which most people aren't.
This is what things like Ember offer you. You can write all of your routes on the client-side, and then the client is responsible for updating state, throwing old objects away, etc. This requires a robust JavaScript implementation of models, views, and controllers to work properly. Otherwise you're going to quickly end up with a pile of rotten spaghetti. If you're going to do this, do not use Backbone. Backbone's router works best for simple things like state. There is simply no clean way to use vanilla Backbone to replace a server-side router.
A hybrid approach is where Backbone's router will shine. You use server-side routes to serve the views/templates, and then you enhance them with Backbone's routes. Here's a few examples of that:
/users/me#mode=edit
, where /users/me
is a typical route served by the server, and #mode=edit
is a Backbone route that changes the view to an 'edit' mode where the user can edit his profile info./calendars/work#date=today
. Here's an example of something you just can't do with a server-side route: highlight a particular cell of the calendar (namely, today
).Unless you're set on writing a one-page app, it's safe to say that you won't benefit too much from using a client-side router. And even if you are writing a one-pager, you probably shouldn't look to Backbone to do it.
Benefits
exception case
just my 2-cents
Edit: deleted " as server-side" in memorable line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With