11

Router in Backbone.js is responsible for routing client-side pages, and connecting them to actions and events based on urls. But how to trigger the url change? I mean if the only way to do this is to enclose the element associated with page routing in <a> tag.

Because I have associated the mousedown and mouseup events with the element used for routing, if I put it in <a> tag, the mousedown and mouseup events will definitely become invalid as it will have conflict with the click event of <a> tag. So is there other ways to make the routing?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
chaonextdoor
  • 5,019
  • 15
  • 44
  • 61

1 Answers1

31

You can use Router#navigate:

navigate router.navigate(fragment, [options])

Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you wish to also call the route function, set the trigger option to true.

So, if your router is r and you want to activate the route for #/some_route, then you could:

r.navigate('some_route', { trigger: true });

Demo (open your console please): http://jsfiddle.net/ambiguous/xkZtB/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • One more question, as I have to access the data in the model to provide the id for my url, such as 'category/:id'. How should I do that? – chaonextdoor Apr 27 '12 at 06:48
  • @chaonextdoor: You should be able to build the appropriate route as a string and hand it to `navigate`: `r.navigate('category/' + m.get('id'), { trigger: true })` – mu is too short Apr 27 '12 at 07:00
  • Hi man, I have another backbone router problem here: [http://stackoverflow.com/questions/10346557/backbone-js-router-initialization-doesnt-run-immediately]. Could you help me fix that? Thanks a lot in advance. – chaonextdoor Apr 27 '12 at 07:40