2013-05-03 24 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

相關問題