Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Autocomplete Plugin using Backbone JS

Let's suppose I want to use jQueryUi for implemeting autocomplete in a backboneView having a form.

I implement the following code (*), but 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 only when the user starts to type something in the input box?

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.:
the fetching should be performed just one time when the user types the first letter.

like image 407
Lorraine Bernard Avatar asked Sep 11 '26 07:09

Lorraine Bernard


1 Answers

This should work and only call fetch once.

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)
    });
  }
});
like image 183
Paul Avatar answered Sep 12 '26 22:09

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!