Quellcode durchsuchen

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
Kevin Brown vor 9 Jahren
Ursprung
Commit
3b8cd2e369
1 geänderte Dateien mit 24 neuen und 1 gelöschten Zeilen
  1. 24 1
      src/js/select2/data/tokenizer.js

+ 24 - 1
src/js/select2/data/tokenizer.js

@@ -21,6 +21,29 @@ define([
   Tokenizer.prototype.query = function (decorated, params, callback) {
   Tokenizer.prototype.query = function (decorated, params, callback) {
     var self = this;
     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) {
     function select (data) {
       self.trigger('select', {
       self.trigger('select', {
         data: data
         data: data
@@ -29,7 +52,7 @@ define([
 
 
     params.term = params.term || '';
     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) {
     if (tokenData.term !== params.term) {
       // Replace the search term if we have the search box
       // Replace the search term if we have the search box