1

What is the 'best practice' way to load a new route in a backbone single page app?

Right now, my app has a mix of these two methods:

1) In my html

<a href="#/foo">Some Route</a>

Or I can define an event in my view:

2) In my view

Backbone.View.extend({
  //init code
  events: {
    'click a':'fooNav'
  },

  fooNav: function(e) {
    e.preventDefault();
    window.location.replace('#/foo');
  }


});

Both work fine, with the router cleaning up zombies and loading the associated view.

I'm not sure if I should be always using method two (which gives me more flexibility to do other things in the function and make non <a> tag click events load routes), or whether I should only use method two when it is absolutely necessary. Is one method much faster than the other? Any gotchas?

Many thanks.

cs_stackX
  • 1,407
  • 2
  • 19
  • 27

1 Answers1

0

I prefer method two because, for example, if i want to change something in the url, i can do it in the view. You can use method two like this:

Backbone.View.extend({
//init code
events: {
'click a':'fooNav'
},

fooNav: function(e) {
e.preventDefault();
Backbone.history.navigate('#/foo');
}
});

In this way, you can add id's to the url and keep track of pages in the browser history