0

I took the base of this code from a gist. It initially worked perfectly when I first fetch()ed the collection and then in render() called tw-bootstap's .typeahead().

However, I have put in a keypress event to try and restrict the size of the data returned by fetch(). The collection data is returned and it is filtered through prepData() fine and arrives at render(). The typeahead is not working, however at that stage. It may be that the backbone event is overriding render at that point?

// typeahead on the numbers
var Bootstrap = {};

Bootstrap.Typeahead = Backbone.View.extend({
    el: '#autocompleteN',
    tagName: 'input',
    attributes: {"data-provide": "typeahead"},
    initialize: function(options){
        if(!this.collection) {
            return null;
        }

        //this.collection.on("reset", this.prepData, this);
    },
    events: {
        "keypress": "setSearch"
    },

    setSearch: _.throttle(function(e) {
        var that=this;
        var d = e.currentTarget.value;

        // strip spaces and remove non-numerics
        d = d.replace(/ /g,'');
        d = d.replace(/[^0-9]/g, '');

        // if it's longer than 2, call a fetch;
        if(d.length > 2) {
            $.when( app.searchNums.fetch({url: 'api/index.php/search/num/'+d}) ).then(function() { 
                //console.dir("success");
                that.prepData();
            });
        }

    }, 1000),
    prepData: function() {
        //console.dir("prepData called");
        var prepare = _.pluck(this.collection.models, 'attributes');
        this.property = this.options.property || _.keys(prepare[0])[0];

        this.items = this.options.items;
        this.data = _.pluck(prepare, this.property);

        this.render();
    },
    render: function() {
        var that = this;
        that.$el.typeahead({
            source: that.data,
            //source: ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'],
            items: that.items,
            onselect: function( data ) {  
                // render the results view here
            }
        });

        return this;
    }
});

var bui = new Bootstrap.Typeahead({
    collection: app.searchNums,
    items: 5
});
Joe
  • 1,841
  • 4
  • 27
  • 43

1 Answers1

0

Why dont you just set minLength on the typeahead, it looks like that is what you are trying to do?

d4kris
  • 528
  • 5
  • 11