假设我想使用jQueryUi在具有表单的backboneView中实现自动完成。
我实现了以下代码(*), 但是我不喜欢它,因为当用户没有输入任何字母时也会执行集合的提取。
只有当用户开始在输入框中输入内容时,我该如何执行提取集合?
var MyView = Backbone.View.extend({
initialize: function () {
this.myCollection = new MyCollection();
this.myCollection.fetch(); // I would like to fetch the collection
// only when the user start to type the first letter
},
events: {
'focus #names': 'getAutocomplete'
},
getAutocomplete: function () {
$("#names").autocomplete({
source: JSON.stringify(this.myCollection)
});
}
});
P.S .:
当用户键入第一个字母时,应该只执行一次提取。
答案 0 :(得分:9)
这应该有效,只能调用一次。
var MyView = Backbone.View.extend({
initialize: function () {
this.myCollection = new MyCollection();
this.collectionFetched = false;
},
events: {
'focus #names': 'getAutocomplete'
'keydown #names': 'fetchCollection'
},
fetchCollection: function() {
if (this.collectionFetched) return;
this.myCollection.fetch();
this.collectionFetched = true;
},
getAutocomplete: function () {
$("#names").autocomplete({
source: JSON.stringify(this.myCollection)
});
}
});
答案 1 :(得分:2)
尝试这样:
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)
});
}
});