使用Backbone JS的jQuery自动完成插件

Lor*_*ard 3 javascript jquery jquery-ui backbone.js

假设我想使用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)
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

PS:
当用户键入第一个字母时,应该只执行一次提取.

Pau*_*aul 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)
    });
  }
});
Run Code Online (Sandbox Code Playgroud)