0

I have a sidebar view with a list of items like so

SideBarView = Backbone.View.extend(
  events:
    "click item": "dosomething"
  render:
    //Render item list from a collection
)

Now, I am trying to display the sidebar view on two different routes but I ran into a little problem. On route A, I want the dosomething() method to print "A", and on route B I want the dosomething() method to print "B". So, I was wondering what is the best approach into this problem? I thought about it and came up with the following 2 approaches but neither seem to be elegant enough.

Approach 1

Make another SideBarView and call it SideBarView2 then change method dosomething to dosomethingForRouteB. So then I can use SideBarView2 for route B. However, this violated the DRY principle; not to mention, lets say I want to change the rendering method for the SideBarView later on then I would have to make changes at two different places. Overall, I think this is a very bad approach

Approach 2

Inside the dosomething() method, I can have the logic statement like so

route = getCurrentRoute()
if(route = "/routeA")
 print A
else
 print B

A little more elegant than approach 1 but having a logical statement inside your view is a bit too hacky.

Anyway, my question is that should I use approach 2 or is there a better approach to this problem?

Thanks

Infinity
  • 3,695
  • 2
  • 27
  • 35

1 Answers1

2

Why don't you let SideBarView accept a parameter of which thing you want to display.

SideBarView = Backbone.View.extend({
    print_value: B,

    events: {...},

    initialize: function(options){
        options = options || {};
        if(options.display === 'A'){
             this.print_value = "A";
        }
     },

     render: function(){ ...}
}

And then in your router:

 route_method: function(path){
     new SideBarView({display: path});
 }
mu is too short
  • 426,620
  • 70
  • 833
  • 800
tkone
  • 22,092
  • 5
  • 54
  • 78
  • Interesting, if no one else has a better answer then I may use this. Thanks! – Infinity Sep 29 '12 at 17:21
  • 1
    There's nothing hacky, by the way, about having a conditional set of logic within your view. We have conditionals in our views that know how to display the page for a user who is authenticated and someone who isn't authenticated. They're the same page, but they have some small differences. Maintaining two separate views would be massive overkill and a breach of the DRY principal. – tkone Sep 29 '12 at 17:23
  • @QuynhNguyen: If the differences start getting bigger you might be able to use partials (assuming your template system supports them) to keep your templates from getting too messy. – mu is too short Sep 29 '12 at 18:58
  • @QuynhNguyen since muistooshort brought that up allow me to shill for [dust.js](https://github.com/linkedin/dustjs) which we use throughout our site. Supports partials, pre-compilation of templates, and a host of other things – tkone Sep 29 '12 at 19:31