Search code examples
javascriptbackbone.jsstatic-content

Backbone: Handling static views


What's the best way to handle static views in Backbone?

My current method is displaying or hiding views with either a css class, or javascript (with or without jquery). An issue occurs when using this method; once the views get too deeply nested, controlling each view becomes complex. An example of my method is my website (code), yet it isn't deeply nested enough to cause an issue.

A suggestion I've had is to go about it as you would with dynamic content, using templates and models, and render the needed views. With that, to decrease the complexity, use marionette which seems perfect for dynamic views.



Solution

  • I'm surprised you're running into an issue when using the toggle class strategy. Can you give a concrete example of a situation where this gets messy? You mention that your site's code isn't a problem, so what is? Where are some bits that smell?

    I say this only because it seems like toggling visibility is really the most straight forward option and you might be over thinking this. Unless I'm misunderstanding your use case. Also, there's not going to be a 'best' answer for this question. It's very situation dependent.

    EDIT:

    This is a high level question that's difficult to answer directly. The crux of what your asking is really "how do I manage complex view state and interaction". The distinction between dynamic/static html doesn't really matter, you're faced with the challenge you outline no matter how you generate your html for the subviews.

    That said, you mention that you're using backbone. Remember that backbone is just a tool to help you architect a solution, if you feel like you're fighting it, perhaps you are.

    Even so, if I were implementing the case in your comment and wanted to stick with backbone conventions, yes, I would do as you mentioned; I'd treat my 'static' views the same as my 'dynamic' ones. Backbone views are less about html and more about interaction contexts - and it sounds like its the interaction context that you really care about.

    So I'd have a View named ProductView that itself had a TabContainerView. This TabContainerView would have TabViews and so on. I'd go down the hierarchy for every level of interaction state that's important. Then it becomes easy to track state and work with the views. Need to track the currently visible tab? Add a property to TabContainerView. Need to hide a pop-up triggered by a TabContainerView, add a hide method to TabContainerView.

    In this way, your view hierarchy is rich with state and event handlers. Further, you can develop things in a widget fashion and use composition to build up a pretty sophisticated experience.

    Hope that helps.