3

Since backbone provides two ways of responding to certain events, I was wondering what the general consensus. This is a very common situation - I have a link on a page, i can set up the href on the page to route it so the router can call a function to handle it, like so:

HTML

 <a href='#posts/2' class='handleInView'>Item 2</a>

JS

var AppRouter = Backbone.Router.extend({
        routes: {
            "posts/:id": "getPost"
        }
    });

or I can respond to the event in the View like so:

var MyView = Backbone.View.extend({
  ...
  events: {
    "click .handleInView":          "open",
  },

  ...

  open: function() {
      ...
  }

});

I know routes provide you with the added benefit of history and direct links, but from a performance standpoint and code layout perspective what is a better approach if I dont care about history.

My routes could be a single place where i can see all of the interactions but it also could get cluttered very quickly.

mithun_daa
  • 4,334
  • 5
  • 38
  • 50

3 Answers3

1

If you don't care about history or bookmarks, events have fewer side effects (people won't try to bookmark them and they won't interfere with your history) and they're simpler / faster to implement and handle.

Performance-wise, they're slightly faster as well (but really neither method is slow enough to matter at all).

hunterloftis
  • 13,386
  • 5
  • 48
  • 50
0

I agree with the comments. Anything that requires deeplinking, bookmarks etc should be handled by using routes. However if you have something like a TabView, or another view that should be inaccessible from a URL, and is nested in another view, then it might make more sense in dealing with that inside of your view code. As for the clutter, you might want to think about reorganizing your routes into separate files. Here are some examples

Backbone general router vs. separate routing files?

Multiple routers vs single router in BackboneJs

Community
  • 1
  • 1
abritez
  • 2,616
  • 3
  • 29
  • 36
0

In general, routes are used when you are calling a drastic change in the state of your application, or you would like to maintain a browsing history (via backbone.history) so the user can navigate back & forth between states via the browser buttons.

Ideally, you would use both in different circumstances.

I like to think of it in terms of what is changing on my page. If the general page state is the same, but certain elements are changing or updating, I will use events. If the general page state is changing or if I'm loading a different UI Screen, I will use routes.

1nfiniti
  • 2,032
  • 14
  • 19