Add the Search Result List View

The view for the search result list doesn’t need a template. It is simply a container for list item views. It tracks these views in the listItemViews member. If the underlying collection changes, it re-renders itself.

  1. In the <script> block that contains the SearchPage view, extend Backbone.View to show a list of search view results. Add an array for list item views and an initialize() function.
    1app.views.UserListView = Backbone.View.extend({
    2    listItemViews: [],
    3    initialize: function() {
    4        this.model.bind("reset", this.render, this);
    5    },

    For the remainder of this procedure, add all code to the extend({}) block.

  2. Create the render() function. This function cleans up any existing list item views by calling close() on each one.
    1render: function(eventName) {
    2    _.each(this.listItemViews, 
    3           function(itemView) { itemView.close(); });
  3. Still in the render() function, create a set of list item views for the records in the underlying collection. Each of these views is just an entry in the list. You define app.views.UserListItemView later.
    1this.listItemViews = _.map(this.model.models, function(model) { return new 
    2    app.views.UserListItemView({model: model}); });
  4. Still in the render() function, append each list item view to the root DOM element and then return the rendered UserListView object.
    1$(this.el).append(_.map(this.listItemViews, function(itemView) {
    2    return itemView.render().el;} ));
    3    return this;
    4}

Example

Here’s the complete extension:
1app.views.UserListView = Backbone.View.extend({
2    
3    listItemViews: [],
4    
5    initialize: function() {
6        this.model.bind("reset", this.render, this);
7    },
8    render: function(eventName) {
9        _.each(this.listItemViews, function(itemView) {
10            itemView.close(); });
11        this.listItemViews = _.map(this.model.models, 
12            function(model) {
13                return new app.views.UserListItemView(
14                    {model: model}); });
15        $(this.el).append(_.map(this.listItemViews, 
16            function(itemView) { 
17                return itemView.render().el;
18            } ));
19        return this;
20    } 
21});