Search code examples
javascriptbackbone.jsbackbone-viewsbackbone.js-collections

Initialising a view on keyup to many views - backbone


I have some search functionality that I am working on, every time a user types into a text input I filter a collection, here is the code,

userSearch: function() {
    var that = this;
    var letters = $('.js-user-search').val();
    this.filteredCollection.reset(that.filterUsers( that.collection, letters));

    var resultsList = new app.SearchUserResults({
        collection: this.filteredCollection
    });

    resultsList.render();
},

filterUsers: function( collection, filterValue) {
    var filteredCollection;

    if (filterValue === "") {
        return collection.toJSON();
    }

    return filteredCollection = collection.filter(function(data) {

        return _.some(_.values(data.toJSON()), function(value) {

            if( value != undefined ) {

                value = (!isNaN(value) ? value.toString() : value);
                //var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

                return value.indexOf(filterValue) >= 0;

            }

        });

    });

}

As you can see from the code above, I pass a collection (users) and the search parameters to filterUsers(), that then returns a collection of matching models. I am then trying to render that into a list of search results ( links ), but the events on those links run several times (dependent on the length of the search string).

How can I build a list of results from the return collection? I have tried adding,

this.filteredCollection.on('reset', this.doSomething); however this never seems to get run, I have tried initialising my results view in the initialise function also, but I cannot pass the collection to that view as it is empty what is the best way to go?


Solution

  • you have to be careful with views in backbone. You keep adding a new searchresults view without removing the old one. Always keep a reference to views you add multiple times so that you can remove the previous one. I think this part will help you out:

    var myCurrentSearchList = null;
    
    userSearch: function() {
      var that = this;
      var letters = $('.js-user-search').val();
      this.filteredCollection.reset(that.filterUsers( that.collection, letters));
      if (myCurrentSearchList) {
        myCurrentSearchList.remove();
      }
      var resultsList = new app.SearchUserResults({
        collection: this.filteredCollection
      });
      myCurrentSearchList = resultsList;
    
      resultsList.render();
    },
    

    http://backbonejs.org/#View-remove