Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Backbone View for jQuery UI Autocomplete inputs
var Autocomplete = Backbone.View.extend({
render: function() {
var choices = this.options.choices,
selected = this.options.selected,
iterator = this.options.iterator,
label = this.options.label,
allowDupes = this.options.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);
};
return this;
}
});
@eric-hu
Copy link

eric-hu commented Nov 15, 2011

link to the article since this gist comes up as a higher result in google

@marksteve
Copy link
Author

marksteve commented Nov 15, 2011

Trimmed of some redundant code (some stuff that Backbone already does w/c aren't really documented) and wrote an example (http://tinkerbin.com/gTmLJuRE).

@xinliu8
Copy link

xinliu8 commented Sep 10, 2012

Links are expired. I'd like to see your article.

@xunker
Copy link

xunker commented Dec 12, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment