Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save seyhunak/1316611 to your computer and use it in GitHub Desktop.
Save seyhunak/1316611 to your computer and use it in GitHub Desktop.
Backbone View for jQuery UI Autocomplete inputs
var Autocomplete = Backbone.View.extend({
initialize: function(options) {
options = _.extend({}, options);
_.bindAll(this, 'refresh');
// Input element
this.input = options.input;
// Choices collection
this.choices = options.choices;
// Selected collection
this.selected = options.selected;
// Iterator to filter results
this.iterator = options.iterator;
// Label callback
this.label = options.label;
// Allow dupes
this.allowDupes = options.allowDupes;
this.choices.bind('refresh', this.refresh);
},
refresh: function(models) {
var choices = this.choices,
selected = this.selected,
iterator = this.iterator,
label = this.label,
allowDupes = this.allowDupes,
$el = $(this.el);
$el.autocomplete({
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), 'i');
response(choices.filter(function(model) {
return iterator(model, matcher);
}));
},
focus: function(event, ui) {
$el.val(label(ui.item));
return false;
},
select: function(event, ui) {
selected.add(ui.item);
if (!allowDupes) {
choices.remove(ui.item);
}
$el.val('');
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li/>')
.data('item.autocomplete', item)
.append($('<a/>').text(label(item)))
.appendTo(ul);
};
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment