1
0
mirror of synced 2025-02-03 21:59:24 +03:00

Create an option when tokenizing if needed

Previously the tokenizer only worked when creating multiple options
at once if all of the options existed. It always worked when creating
a single option, because all of the special cases were handled by the
tagging module. When working with multiple options, the tagging
module does not kick in until after the query has been run, which
is when the tokenizer does its magic.

This fixes the issue by automatically creating the option tags that
the tagging module would normally create. It only does this if the
options do not already exist, so we don't need to worry about the
tokenizer creating duplicates of existing options.

This closes https://github.com/select2/select2/issues/3458
This commit is contained in:
Kevin Brown 2016-03-27 18:29:01 -04:00
parent cfb66f5e4f
commit 3b8cd2e369

View File

@ -21,6 +21,29 @@ define([
Tokenizer.prototype.query = function (decorated, params, callback) {
var self = this;
function createAndSelect (data) {
// Normalize the data object so we can use it for checks
var item = self._normalizeItem(data);
// Check if the data object already exists as a tag
// Select it if it doesn't
var $existingOptions = self.$element.find('option').filter(function () {
return $(this).val() === item.id;
});
// If an existing option wasn't found for it, create the option
if (!$existingOptions.length) {
var $option = self.option(item);
$option.attr('data-select2-tag', true);
self._removeOldTags();
self.addOptions([$option]);
}
// Select the item, now that we know there is an option for it
select(item);
}
function select (data) {
self.trigger('select', {
data: data
@ -29,7 +52,7 @@ define([
params.term = params.term || '';
var tokenData = this.tokenizer(params, this.options, select);
var tokenData = this.tokenizer(params, this.options, createAndSelect);
if (tokenData.term !== params.term) {
// Replace the search term if we have the search box