Add the Search Result List Item View
To define the search result list item view, you design and implement the view of a single row in
a list. Each list item displays the following user fields:
- SmallPhotoUrl
- FirstName
- LastName
- Title
-
Immediately after the UserListView view definition, create
the view for the search result list item. Once again, extend Backbone.View and indicate that this view is a
list item by defining the tagName member.
For the remainder of this procedure, add all code in the extend({}) block.
1app.views.UserListItemView = Backbone.View.extend({ 2 3}); -
Add an <li> tag.
1app.views.UserListItemView = Backbone.View.extend({ 2 tagName: "li", 3}); -
Load the template by calling _.template() with the raw
content of the user-list-item script.
1template: _.template($("#user-list-item").html()), -
Add a render() function. The template() function, from underscore.js,
takes JSON data and returns HTML crafted from the associated template. In this
case, the function extracts the customer’s data from JSON and returns HTML that
conforms to the user-list-item template.
During the conversion to HTML, the template() function replaces free variables in the template with
corresponding properties from the JSON data.
1render: function(eventName) { 2 $(this.el).html(this.template(this.model.toJSON())); 3 return this; 4}, -
Add a close() method to be called from the list view that
does necessary cleanup and stops memory leaks.
1close: function() { 2 this.remove(); 3 this.off(); 4}
Example
Here’s the complete
extension.
1app.views.UserListItemView = Backbone.View.extend({
2 tagName: "li",
3 template: _.template($("#user-list-item").html()),
4 render: function(eventName) {
5 $(this.el).html(this.template(this.model.toJSON()));
6 return this;
7 },
8 close: function() {
9 this.remove();
10 this.off();
11 }
12});