From 6e490628d1be1a165d95ecf9817fdc7070069947 Mon Sep 17 00:00:00 2001 From: Jacob Thornton <jacobthornton@gmail.com> Date: Sat, 21 Jan 2012 22:06:36 -0800 Subject: [PATCH] more efficient matcher + bold matched query in item --- js/bootstrap-typeahead.js | 50 +++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/js/bootstrap-typeahead.js b/js/bootstrap-typeahead.js index 16539fefbf..b8ff5aab00 100644 --- a/js/bootstrap-typeahead.js +++ b/js/bootstrap-typeahead.js @@ -36,7 +36,7 @@ , matcher: function (item, query) { // ;_; http://jsperf.com/asdfdfasdfa - return ~item.toLowerCase().indexOf(query.toLowerCase()) + return ~item.toLowerCase().indexOf(query) } , select: function () { @@ -67,16 +67,20 @@ } , lookup: function (event) { - var query = this.$element.val() - , that = this + var that = this , items + , q + + this.query = this.$element.val() - if (!query) { + if (!this.query) { return this.shown ? this.hide() : this } + q = this.query.toLowerCase() + items = this.data.filter(function (item) { - if (that.matcher(item, query)) return item + if (that.matcher(item, q)) return item }) if (!items.length) { @@ -88,10 +92,15 @@ , render: function (items) { var that = this + , QUERY = new RegExp('(' + this.query + ')', 'ig') items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) - i.find('a').text(item) + + i.find('a').html(item.replace(QUERY, function ($1, match) { + return '<strong>' + match + '</strong>' + })) + return i[0] }) @@ -122,6 +131,21 @@ prev.addClass('active') } + , listen: function () { + this.$element + .on('blur', $.proxy(this.blur, this)) + .on('keypress', $.proxy(this.keypress, this)) + .on('keyup', $.proxy(this.keyup, this)) + + if ($.browser.webkit || $.browser.msie) { + this.$element.on('keydown', $.proxy(this.keypress, this)) + } + + this.$menu + .on('click', $.proxy(this.click, this)) + .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) + } + , keyup: function (e) { e.stopPropagation() e.preventDefault() @@ -188,20 +212,6 @@ $(e.currentTarget).addClass('active') } - , listen: function () { - this.$element - .on('blur', $.proxy(this.blur, this)) - .on('keypress', $.proxy(this.keypress, this)) - .on('keyup', $.proxy(this.keyup, this)) - - if ($.browser.webkit || $.browser.msie) { - this.$element.on('keydown', $.proxy(this.keypress, this)) - } - - this.$menu - .on('click', $.proxy(this.click, this)) - .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) - } } -- GitLab