开发者

How do you append your sub-views in Backbone?

I have a Backbone app that renders several related views on each page they you navigate to. For example, one page renders the following views:

  • Context bar
    • Drop-down menus
    • Pagination
  • Main table
    • Table rows

The main table view here is the first to be appended to the DOM by my router - within this view reset is bound to an appendRows function within it - which addes in each table row:

// Instanti开发者_StackOverflowate the view, render and append it to the DOM
var tableView = new TableView({ collection: blahCollection });
$("main").append(tableView.render().el);

// Fetch the latest data for the collection (triggers a reset which appends rows)
blahCollection.fetch();

This seems logical to me, however when it comes to adding in a pagination sub-view for example, I ask myself the question, "should a view really be controlling what is appended to the screen"?

Therefore, given the pagination example:

  • Should a view (in this case the main table view) control how/when pagination is appended to the DOM?
  • Should the router? If so, should it call a function on the parent view to do this - or should the logic be kept completely outside of the main view?


I like letting my router do a lot of the high-level stuff for me. For instance, I will set up a basic layout... something like this:

<body>
    <div id="contextBar">
        <div id="menus"></div>
        <div id="pagination"></div>
    </div>
    <div id="mainTable"></div>
</body>

Then, in my router handler, I'd hook up the views that are unrelated to each other:

var contextView = new ContextView({el: $("#contextBar")});
var menusView = new MenusView({el: $("#menus")});
var paginationView = new PaginationView({el: $("#pagination")});
var tableView = new MainTableView({el: $("#mainTable")});

As far as the main table goes, I see the table view and the rows view being tightly coupled as they are directly related to each other, so I usually have the collection view (your table view) create and manage the individual item views (your table row view).

At least, that is how I organize my code with Backbone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜