Merge branch 'hotfix/21.56.9' into master
[gitter.git] / public / js / views / modals / filtered-select.js
blob13733e330cbee213600cb6be07dd7b6ac0f9461d
1 'use strict';
3 var Marionette = require('backbone.marionette');
4 var Typeahead = require('../controls//typeahead');
5 var SimpleFilteredCollection = require('gitter-realtime-client/lib/simple-filtered-collection');
7 var FilteredSelect = Marionette.ItemView.extend({
8   events: {
9     focus: 'onActivate',
10     blur: 'hide',
11     click: 'onActivate'
12   },
14   initialize: function(options) {
15     this.filter = options.filter;
16     this.collection = options.collection;
17     this.itemTemplate = options.itemTemplate;
18     this.dropdownClass = options.dropdownClass;
20     this.filteredCollection = new SimpleFilteredCollection([], {
21       collection: this.collection
22     });
23     this.refilter('', this.filteredCollection);
25     this.typeahead = new Typeahead({
26       el: this.el,
27       disableShowOnAdd: true,
28       disableListenToChange: true,
29       longDebounce: 200,
30       shortDebounce: 50,
31       collection: this.filteredCollection,
32       itemTemplate: this.itemTemplate,
33       dropdownClass: this.dropdownClass,
34       fetch: this.refilter.bind(this),
35       autoSelector: function(input) {
36         return function(model) {
37           this.filter(input, model);
38         }.bind(this);
39       }.bind(this)
40     });
42     this.listenTo(this.typeahead, 'selected', this.selected);
43     this.listenTo(this.collection, 'add remove change reset sync', this.reset);
44   },
46   getSelected: function() {
47     return this.selectedGroup;
48   },
50   selected: function(item) {
51     this.hide();
52     this.trigger('selected', item);
53   },
55   onDestroy: function() {
56     this.typeahead.destroy();
57   },
59   onActivate: function() {
60     if (this.el.value) {
61       this.show();
62     }
63   },
65   show: function() {
66     if (this.typeahead) {
67       this.typeahead.show();
68     }
69   },
71   hide: function() {
72     if (this.typeahead) {
73       this.typeahead.hide();
74     }
75   },
77   refilter: function(input, collection, success) {
78     collection.setFilter(
79       function(model) {
80         return this.filter(input, model);
81       }.bind(this)
82     );
84     if (success) success();
85   }
86 });
88 module.exports = FilteredSelect;