1 | import { wrap } from 'underscore';
|
2 | import Backbone from 'backbone';
|
3 | import globalize from './internal/globalize';
|
4 | import ResultSet from './result-set';
|
5 |
|
6 | var ResultsList = Backbone.View.extend({
|
7 | events: {
|
8 | 'click [data-id]': 'setSelection'
|
9 | },
|
10 |
|
11 | initialize: function (options) {
|
12 | if (!this.model) {
|
13 | this.model = new ResultSet({source: options.source});
|
14 | }
|
15 |
|
16 | if (!(this.model instanceof ResultSet)) {
|
17 | throw new Error('model must be set to a ResultSet');
|
18 | }
|
19 |
|
20 | this.model.bind('update', this.process, this);
|
21 |
|
22 | this.render = wrap(this.render, function (func) {
|
23 | this.trigger('rendering');
|
24 | func.apply(this, arguments);
|
25 | this.trigger('rendered');
|
26 | });
|
27 | },
|
28 |
|
29 | process: function () {
|
30 | if (!this._shouldShow(this.model.get('query'))) {
|
31 | return;
|
32 | }
|
33 | this.show();
|
34 | },
|
35 |
|
36 | render: function () {
|
37 | var ul = Backbone.$('<ul/>');
|
38 | this.model.each(function (model) {
|
39 | Backbone.$('<li/>').attr('data-id', model.id).html(this.renderItem(model)).appendTo(ul);
|
40 | }, this);
|
41 | this.$el.html(ul);
|
42 | return this;
|
43 | },
|
44 |
|
45 | renderItem: function () {
|
46 | return;
|
47 | },
|
48 |
|
49 | setSelection: function (event) {
|
50 | var id = event.target.getAttribute('data-id');
|
51 | var selected = this.model.setActive(id);
|
52 | this.trigger('selected', selected);
|
53 | },
|
54 |
|
55 | show: function () {
|
56 | this.lastQuery = this.model.get('query');
|
57 | this._hiddenQuery = null;
|
58 | this.render();
|
59 | this.$el.show();
|
60 | },
|
61 |
|
62 | hide: function () {
|
63 | this.$el.hide();
|
64 | this._hiddenQuery = this.lastQuery;
|
65 | },
|
66 |
|
67 | size: function () {
|
68 | return this.model.get('length');
|
69 | },
|
70 |
|
71 | _shouldShow: function (query) {
|
72 | return query === '' || !(this._hiddenQuery && this._hiddenQuery === query);
|
73 | }
|
74 | });
|
75 |
|
76 | globalize('ResultsList', ResultsList);
|
77 |
|
78 | export default ResultsList;
|