Backbone showing/hiding rendered views best practices

13,555

Solution 1

We are using a global variable App with several common function used across application:

var App = {
    initialize : function() {

        App.views = {
            clientView : new ClientsView(),
            clientItemView : new ClientsItemsView()
        }
    },

    showView: function(view){
        if(App.views.current != undefined){
            $(App.views.current.el).hide();
        }
        App.views.current = view;
        $(App.views.current.el).show();
    },

    ...
}

And then I use this App from other parts of application:

App.showView(App.views.clientView);

Solution 2

IntoTheVoid's solution is good – it's nice to have a single place to hide/show views. But how do you activate the logic?

In my experience, routers are the best place for this. When a route changes and the appropriate function is called, you should update the active, visible view(s).

What if you need multiple views to be visible at once? If you have a primary view that always changes when the route changes, and multiple subsidiary sticky views, you need not worry. But if it's more complex than that, think of creating a ComboView that neatly packages all the relevant views into one containing el node. That way the above logic still works, and your router functions are not littered with logic for managing what views are visible at the moment.

Share:
13,555
Brandon
Author by

Brandon

Updated on June 15, 2022

Comments

  • Brandon
    Brandon almost 2 years

    New to using Backbone and have a very simple application. Basically there are Clients and ClientItems. I have a view to show all Clients and if you click on a Client you get taken to their ClientItems. Going to this ClientItems view should just hide the Clients view and going back to Clients should hide ClientItems. Now, in my render() function for each view, it is going through the collections and dynamically adding stuff to the page. When I go back and forth between the two (using the back button) I don't really need to fully render again as all the data is there in the page, just hidden. Where should this logic go? Right now I have it in the render() function but it feels sloppy, what is the preferred way of handling this?

  • Brandon
    Brandon about 12 years
    Looks good. I see that you create the Views right off the bat in initialize. Is this a common thing to do? Would you do the same with collections? Makes sense to me now since I'm only ever going to need a single instance of either but I am still learning.
  • Admin
    Admin about 12 years
    we are just creating the views right away, all other stuff are created when needed. You could of course add require.js, and init view when first required.
  • Montana Harkin
    Montana Harkin about 11 years
    We are using App.views.current.show() so that any additional logic with respect to showing can be performed there (there may be other event listeners that change)