浏览代码

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 9 年之前
父节点
当前提交
3b8cd2e369
共有 1 个文件被更改,包括 24 次插入1 次删除
  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) {
     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