Forked from marksteve/Backbone.View.Autocomplete.js
Created
October 26, 2011 15:01
-
-
Save seyhunak/1316611 to your computer and use it in GitHub Desktop.
Backbone View for jQuery UI Autocomplete inputs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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