Let's suppose I want to use jQueryUi.autocomplete
for making a module which take the source from a backboneCollection
.
I implement the following code (1) for the autocomplete module and
the following for the Backbone.view (2).
Actually, I don't like it because the fetching of the collection is performed also when the user does not type any letter.
How should I perform the fetching collection
or the source function
only when the user starts to type something in the input box?
P.S.:
I have already posted a similar question jQuery Autocomplete Plugin using Backbone JS ,
but since the needs of aoutocomplete module could be shared between different view I decided to move the fetch of the collection in autocomplete module.
(1)
/*global define */
define([
'users',
'jquery',
'jqueryUi'
], function (UserCollection, $) {
"use strict";
var autoComplete = function(element) {
var userCollection,
data;
userCollection = new UserCollection();
userCollection.fetch();
data = userCollection.toJSON();
element.autocomplete({
minLength: 3,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(data, function(value) {
return matcher.test(value.name);
}));
},
create: function() {
element.val(data.name);
},
focus: function(event, ui) {
element.val(ui.item.name);
return false;
},
select: function(event, ui) {
element.val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a><img src="' + item.avatar + '" />' + item.name + '<br></a>')
.appendTo(ul);
};
};
return autoComplete;
});
(2)
// View1 (view using the module autocomplete)
define([
'autoCompleteModule'
], function (autoCompleteModule) {
var MyView = Backbone.View.extend({
events: {
'focus #names': 'getAutocomplete'
},
getAutocomplete: function (e) {
autoCompleteModule($('#names'));
}
});
});