charliexx
charliexx

Reputation: 433

Bootstrap typeahead suggestions replaced when navigation

I'm using Bootstrap Typeahead to suggest som search results. The results are returned from a ajax ressource, and since this resource creates a delay, I'm experiencing a unfortunate effect.

Example: If typing a 4 letter word, the suggestions will appear after 2 letters, I can then go through the results with the keys up/down, but suddenly the suggestions will reload because the last request has finished.

Is there any way to "cancel" any remaining, if user is currently using the keys up/down to go through the suggestions?

('#query').typeahead({
        items: 4,
        source: function (query,process) {

            map = {};
            $.getJSON('/app_dev.php/ajax/autosuggest/'+query, function (data) {
                vehicles = [];
                $.each(data, function(i,vehicle){
                    map[vehicle.full] = vehicle;
                    vehicles.push(vehicle.full);
                });
                process(vehicles);
            });
        },
        updater: function (item) {
            // do something here when item is selected
        },
        highlighter: function (item) {
            return item;
        },
        matcher: function (item) {
            return true;
        }
    });

Upvotes: 4

Views: 558

Answers (1)

davidkonrad
davidkonrad

Reputation: 85528

I think the following will satisfy your needs (its hard to reproduce exactly) :

There is no easy way to abort a delayed response, but you could extend typeahead as I figured out here (without modifying bootstrap.js)

The concept is to catch keydown, detect if the event is KEY_UP or KEY_DOWN, set a flag is_browsing, and then abort process if is_browsing is true (that is, if the user has hitted KEY_UP or KEY_DOWN and no other keys afterwards).

Extending typeahead :

// save the original function object
var _superTypeahead = $.fn.typeahead;

// add is_browsing as a new flag
$.extend( _superTypeahead.defaults, {
    is_browsing: false
});

// create a new constructor
var Typeahead = function(element, options) {
    _superTypeahead.Constructor.apply( this, arguments )
}

// extend prototype and add a _super function
Typeahead.prototype = $.extend({}, _superTypeahead.Constructor.prototype, {
    constructor: Typeahead

    , _super: function() {
        var args = $.makeArray(arguments)
        // call bootstrap core
        _superTypeahead.Constructor.prototype[args.shift()].apply(this, args)
    }

    //override typeahead original keydown
  , keydown: function (e) {
      this._super('keydown', e)
      this.options.is_browsing = ($.inArray(e.keyCode, [40,38])>-1)
    }

    //override process, abort if user is browsing
  , process: function (items) {
      if (this.options.is_browsing) return
      this._super('process', items)
    }

});

// override the old initialization with the new constructor
$.fn.typeahead = $.extend(function(option) {
    var args = $.makeArray(arguments),
    option = args.shift()

    // this is executed everytime element.modal() is called
    return this.each(function() {
        var $this = $(this)
        var data = $this.data('typeahead'),
            options = $.extend({}, _superTypeahead.defaults, $this.data(), typeof option == 'object' && option)

        if (!data) {
            $this.data('typeahead', (data = new Typeahead(this, options)))
        }
        if (typeof option == 'string') {
            data[option].apply( data, args )
        }
    });
}, $.fn.typeahead);

This typeahead-extension could be placed anywhere, eg in a <script type="text/javascript"> -section

Testing the extension :

<input type="text" id="test" name="test" placeholder="type some text" data-provide="typeahead">
<script type="text/javascript">
$(document).ready(function() {
    var url='typeahead.php';
    $("#test").typeahead({
        items : 10,
        source: function (query, process) {
            return $.get(url, {  query: query }, function (data) {
                return process(data.options);
            });
        }
    });
});
</script>

A "serverside" PHP script that returns a lot of randomized options with forced delay, typeahead.php :

<?
header('Content-type: application/json');
$JSON='';
sleep(3); //delay execution in 3 secs
for ($count=0;$count<30000;$count++) {
    if ($JSON!='') $JSON.=',';
    //create random strings
    $s=str_shuffle("abcdefghijklmnopq");
    $JSON.='"'.$s.'"';
}
$JSON='{ "options": ['.$JSON.'] }';
echo $JSON;
?>

It really seems to work for me. But I cannot be sure that it will work in your case. Let me now if you have success or not.

Upvotes: 2

Related Questions