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 therender() 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) {
    2  return new app.views.UserListItemView({ model: model });
    3});
  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  listItemViews: [],
3
4  initialize: function () {
5    this.model.bind("reset", this.render, this);
6  },
7  render: function (eventName) {
8    _.each(this.listItemViews, function (itemView) {
9      itemView.close();
10    });
11    this.listItemViews = _.map(this.model.models, function (model) {
12      return new app.views.UserListItemView({ model: model });
13    });
14    $(this.el).append(
15      _.map(this.listItemViews, function (itemView) {
16        return itemView.render().el;
17      }),
18    );
19    return this;
20  },
21});

We've Moved

Welcome to the new home of the Mobile SDK Developer Guide! For now, the Japanese guide can be found in PDF form.