2013-05-03 22 views
2

我通过引导简单的扁平json数组字符串(如["php","php4","php5"])获得了键入工作的帮助。在这种情况下,所有的标准函数都可以做我想要的。自引导键入json对象而不是字符串

不过我想给像下面这样的格式的数据:

[ 
    { 
     "name":"php", 
     "count":123 
    }, 
    { 
     "name":"php4", 
     "count":3532 
    }, 
    { 
     "name":"php5", 
     "count":999 
    } 
] 

有了这样的,我想格式化我的预输入同时使用的名称和数量。也许会产生一些看起来像php5(999)的东西,当您选择typeahead时,它只会输出php5。我想如果我只是覆盖所有的功能,很容易做到。

$('.input-classname').typeahead({ 
     source: function (query, process) { 
      // Source here 
     }, 
     updater: function (item) { // What gets sent to the input box 
      return item.name; 
     }, 
     highlighter: function(item) { 
      return item.name + " (" + item.count + ")"; 
     }, 
     matcher: function (item) { 
      // Do the matching 
     }, 
     sorter: function (items) { 
      // Do the sorting 
     } 
    }); 

这工作得很好,但我想用基地版本highlightermatcher,并且sorter做繁重的工作。我只是通过item.name而不是item。但是我不知道如何获得这些函数的基本版本。有没有办法做到这一点?

回答

1

当然,只需调用/应用Typeahead原型的方法,例如,

var Typeahead = $.fn.typeahead.Constructor; 

$(".input-classname").typeahead({ 
    // ... 
    matcher: function (item) { 
    // do something with item 
    return Typeahead.prototype.matcher.call(this, item); 
    }, 

    sorter: function (items) { 
    // alternatively 
    // do something with items 
    return this.constructor.prototype.sorter.call(this, items); 
    } 
}); 
+0

分拣机不起作用。它接受字符串列表,而不是对象列表 - 如果将对象名称映射到字符串,则高亮显示器item.name将不起作用。 – alekwisnia 2014-01-15 17:42:41

+0

答案的要点是如何在可以调用原件的情况下修补原型方法。更新了代码,以使这两个示例刚刚通过。 – numbers1311407 2014-01-15 18:14:25

相关问题