我扩展了bootstrap-typeahead以获取对象而不是字符串。
它的工作原理,但我想知道这是做事情的正确方法。扩展bootstrap-typeahead以获取对象而不是字符串
谢谢。
参考:
http://twitter.github.com/bootstrap/javascript.html#typeahead http://twitter.github.com/bootstrap/assets/js/bootstrap-typeahead.js
_.extend($.fn.typeahead.Constructor.prototype, {
render: function (items) {
var that = this;
items = $(items).map(function (i, item) {
i = $(that.options.item)
.attr('data-value', item[that.options.display])
.attr('data-id', item.id);
i.find('a').html(that.highlighter(item));
return i[0];
});
items.first().addClass('active');
this.$menu.html(items);
return this;
},
select: function() {
var val = this.$menu.find('.active').attr('data-value'),
id = this.$menu.find('.active').attr('data-id');
this.$element
.val(this.updater(val, id))
.change();
return this.hide()
}
});
return function (element, options) {
var getSource = function() {
return {
id: 2,
full_name: 'first_name last_name'
};
};
element.typeahead({
minLength: 3,
source: getSource,
display: 'full_name',
sorter: function (items) {
var beginswith = [],
caseSensitive = [],
caseInsensitive = [],
item,
itemDisplayed;
while (item = items.shift()) {
itemDisplayed = item[this.options.display];
if (!itemDisplayed.toLowerCase().indexOf(this.query.toLowerCase())) {
beginswith.push(item);
} else if (~itemDisplayed.indexOf(this.query)) {
caseSensitive.push(item);
} else {
caseInsensitive.push(item);
}
}
return beginswith.concat(caseSensitive, caseInsensitive);
},
highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
return item[this.options.display].replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
});
},
matcher: function (item) {
var value = item[this.options.display];
return {
value: ~value.toLowerCase().indexOf(this.query.toLowerCase()),
id: item.id
};
},
updater: function (item, userId) {
options.hiddenInputElement.val(userId);
return item;
}
});
};
以下作品我看不出你是如何甚至还让远。当我尝试运行代码时,会在'sorter()'方法中引发异常,以尝试在对象上应用字符串方法。你是否在改变这种方法?或者可能添加功能的对象? – merv
是的,你是对的,因为我做了其他改变,我没有发布..我会在稍后做。谢谢 –
是的,这样做会很有帮助,因为'matcher()'和'sorter()'在将'items'传递给'render()'方法之前都会改变'items'。此外,API中支持重写'sorter()',因此不需要在** bootstrap-typeahead.js **源文件中编辑它。 (不是说那就是你正在做的 - 只是指出来) – merv