4
votes

I'm hoping to get your general ideas about how to use nested models and views with backbone.js.

Say you have a bunch of dialogs and each dialog has a bunch of tabs. A particular tab may get reused in more than one dialog. Each tab is very different and you may want to add a new tab to the dialog dynamically.

It seems logical to me to have different views for each tab. Also, the dialog should be a view. I'm just a little unclear about how the models and views all fit together.

This is my main question:

If a parent view wants to render child views, it probably needs to actually do something like:

var childView = new ChildView();

And then, use jQuery to

this.$("#listOfChildViews").append(childView.el);

To ensure that the list is cleared before we add, we need to

this.$("#listOfChildViews").html("");

Is this the preferred way of doing this? Seems a little bad to me because of ripping out the whole list and then creating all new objects and adding them in there all at once. Would be perhaps nicer if there was not a 'render' function per se, but rather a 'renderInitially' and then simply 'add' (for adding new childviews).

Sorry this isn't too coherent!

1
Don't forget to unbind all the nested views.Dmitry Polushkin

1 Answers

5
votes

Nick,

I think you should throw in the power of Backbone Models.

Have a Dialog model (or maybe a TabContainer, as Dialog sounds more like a view concept). Each dialog has a collection of Tabs (tab again is from the view universe).

In the initial render, in the DialogView, you show the entire dialog.tabs collection, each one in a TabView.

Then, in the DialogView, you can listen on the events from the tabs collection of the dialog model (add, remove, reset) and add/remove only the views that correspond to the elements that changed.

You have to create the functions that add/remove views yourself. The add function would create and render a view for the added tab, and add it to this.$("#listOfChildViews").

Hope that helps.