Add the Search View
To create the view for a screen, you extend Backbone.View. Let’s start by defining the search view. In this extension, you load the template, define subviews and event handlers, and implement the functionality for rendering the views and performing a SOQL search query.
-
In the <script> block where you defined the User and
UserCollection models, create a Backbone.View extension named SearchPage in the app.views
array.
1app.views.SearchPage = Backbone.View.extend({ 2});For the remainder of this procedure, add all code to the extend({}) block. Each step adds another item to the implementation list and therefore ends with a comma, until the last item.
-
Load the search-page template by calling the _.template() function. Pass it the raw
HTML content of the search-page script tag.
1template: _.template($("#search-page").html()), -
Add a keyup event. You define the search handler function a little later.
1events: { 2 "keyup .search-key": "search" 3}, -
Instantiate a subview named UserListView that contains the
list of search results. (You define app.views.UserListView later.)
1initialize: function() { 2 this.listView = new app.views.UserListView({model: this.model}); 3}, -
Create a render() function for the search page view.
Rendering the view consists of loading the template as the app’s HTML
content. Restore any criteria previously typed in the search field and render
the subview inside the <ul>
element.
1render: function(eventName) { 2 $(this.el).html(this.template()); 3 $(".search-key", this.el).val(this.model.getCriteria()); 4 this.listView.setElement($("ul", this.el)).render(); 5 return this; 6}, -
Implement the search function. This function is the
keyup event handler that performs a
search when the customer types a character in the search field.
1search: function(event) { 2 this.model.setCriteria($(".search-key", this.el).val()); 3 this.model.fetch(); 4}
Example
Here’s the complete
extension.
1app.views.SearchPage = Backbone.View.extend({
2 template: _.template($("#search-page").html()),
3 events: {
4 "keyup .search-key": "search"
5 },
6 initialize: function() {
7 this.listView = new app.views.UserListView({model: this.model});
8 },
9 render: function(eventName) {
10 $(this.el).html(this.template());
11 $(".search-key", this.el).val(this.model.getCriteria());
12 this.listView.setElement($("ul", this.el)).render();
13 return this;
14 },
15 search: function(event) {
16 this.model.setCriteria($(".search-key", this.el).val());
17 this.model.fetch();
18 }
19});