假设我想使用 jQueryUi.autocomplete
来制作一个从 backboneCollection
获取源代码的模块。
我为自动完成模块实现以下代码 (1) 和
以下为Backbone.view (2)。
实际上,我不喜欢它,因为当用户不输入任何字母时也会执行集合的获取。
只有当用户开始在输入框中输入内容时,我应该如何执行获取集合
或源函数
?
附注:
我已经发布过类似的问题jQuery Autocomplete Plugin using Backbone JS ,
但由于 aoutocomplete 模块的需求可以在不同 View 之间共享,我决定将集合的获取移到自动完成模块中。
(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'));
}
});
});
最佳答案
//来自jQuery Autocomplete Plugin using Backbone JS的伪代码
var MyView = Backbone.View.extend({
initialize: function () {
this.myCollection = new MyCollection();
},
events: {
'focus #names': 'getAutocomplete',
'keydown #names':'invokefetch'
},
invokefetch : function(){
this.myCollection.fetch();
$("#names").unbind( "keydown", invokefetch);
},
getAutocomplete: function () {
$("#names").autocomplete({
source: JSON.stringify(this.myCollection)
});
}
});
EDIT-20120711--------- 这个怎么样:
//伪代码...
// View1 (view using the module autocomplete)
define([
'autoCompleteModule'
], function (autoCompleteModule) {
var MyView = Backbone.View.extend({
events: {
'keydown #names': 'getAutocomplete'
},
getAutocomplete: function (e) {
var el = $('#names');
if(!el.data){
autoCompleteModule(el);
}
}
});
});
关于使用 jQueryUI.autocomplete 和 Backbone JS 的 Javascript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420391/