Extendí el booteo-typeahead para tomar un objeto en lugar de una cadena.
Funciona, pero me gustaría saber que esta es la manera correcta de hacer las cosas.Extienda el encabezado de bootstrap-type para tomar un objeto en lugar de una cadena
Gracias.
Referencia:
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;
}
});
};
no veo cómo se están recibiendo incluso tan lejos. Cuando intento ejecutar su código, se lanza una excepción en el método 'sorter()' para intentar aplicar métodos de cadena en objetos. ¿Estabas alterando ese método? ¿O tal vez agregar funciones a los objetos? – merv
sí, tienes razón porque hice otros cambios que aún no publiqué ... Lo haré más tarde. gracias –
Sí, eso sería útil, ya que 'matcher()' y 'sorter()' alteran 'items' antes de pasarlo al método' render() '. Además, se admite la anulación de 'sorter()' en la API, por lo que no debería ser necesario editarla en la fuente ** bootstrap-typeahead.js **. (No dice que eso es lo que estaba haciendo, solo lo señala) – merv