Twitter bootstrap Twitter引导:用于无匹配的Typeahead函数

Twitter bootstrap Twitter引导:用于无匹配的Typeahead函数,twitter-bootstrap,bootstrap-typeahead,Twitter Bootstrap,Bootstrap Typeahead,我有一个“添加新事物”表单,它将“用户”与“事物”关联起来 我正在使用Twitter引导程序Typeahead在键入时提供一个用户列表。 它工作得很好,如果列表中有用户,我可以选择它 但是如果用户不存在,我想显示一个“创建新用户”链接 所以基本上,我需要在.typeahead中的某个地方使用某种形式的“no matches”函数。我算不出来。扩展typeahead类: var newusertext = 'New user'; var newuserlink = '/add/user/0';

我有一个“添加新事物”表单,它将“用户”与“事物”关联起来

我正在使用Twitter引导程序Typeahead在键入时提供一个用户列表。 它工作得很好,如果列表中有用户,我可以选择它

但是如果用户不存在,我想显示一个“创建新用户”链接


所以基本上,我需要在.typeahead中的某个地方使用某种形式的“no matches”函数。我算不出来。

扩展typeahead类:

var newusertext = 'New user';
var newuserlink = '/add/user/0';

$.fn.typeahead.Constructor.prototype.process = function (items) {
      var that = this

      items = $.grep(items, function (item) {
        return that.matcher(item)
      })

      items = this.sorter(items)

      if (!items.length) {
         return this.rendernonmatch().show()
      }

      return this.render(items.slice(0, this.options.items)).show()
    } 


$.fn.typeahead.Constructor.prototype.rendernonmatch = function () {
      var that = this
      var items = new Array();
      items.push(newusertext)
      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })
      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

/* redirect to the registration page to add a new user */    
$.fn.typeahead.Constructor.prototype.updater = function (item) {
      if(item === newusertext){ window.location =  newuserlink; return}
      return item
    }      
请参阅:

我使用了typeahead notFound'template'选项,从那里我可以设置一个链接按钮,这对我来说更容易访问。提前输入设置:

$('#remote .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
  },
  {
    name: 'sn-tags',
    display: 'tag',
    source: oBusqTags, //Bloodhound object
    templates: {
      notFound: '<p>No matches<br><a id="btnAddNewTag" href="#">Add New Tag</a></p>'
    }
}).bind("typeahead:select", function(obj, datum, name) {
  //add selection as an option on a select element
  $('#lbxAddTag').append($('<option>', {
    value: datum.id,
    text: datum.tag
  }));
});
这是该链接的侦听器:

$('#remote').on('click', '#btnAddNewTag', function(e){
    $('#lbxAddTag').append($('<option>', {
        value: "0",
        // this is tricky, as there aren't any matches then 
        // $('#remote .typeahead').typeahead('val') contains '', 
        // so i had to set an id for the typeahead input text box and 
        // 'manually' get its value
        text: $('#tbxBusqTag').val()
    }));
    // as the text is already added as a select option
    // i clean the typeahead input box
    $('#remote .typeahead').typeahead('val','');
    e.preventDefault();
});