From 315b1b3c12e40dc030dff8df4b2e3466b9dc8de6 Mon Sep 17 00:00:00 2001 From: Kevin Brown Date: Sat, 30 Aug 2014 20:25:32 -0400 Subject: [PATCH] Added array adapter This should add support for dynamically generated array data that still works with a basic ` + +
+ + + +
+ + + + + + + diff --git a/playground/basic/decorators.html b/playground/basic/decorators.html index 8e6f3d24..a44b61ef 100644 --- a/playground/basic/decorators.html +++ b/playground/basic/decorators.html @@ -178,11 +178,11 @@ require(["select2/core", "select2/utils", "select2/selection/single", this.$container = $container; - this.$clear.on("click", function (evt) { + this.$clear.on("mousedown", function (evt) { evt.stopPropagation(); var $first = $container.find("li").first(); - $first.click(); + $first.mouseup(); }); }; diff --git a/src/js/select2/data/array.js b/src/js/select2/data/array.js new file mode 100644 index 00000000..5c7bf1c7 --- /dev/null +++ b/src/js/select2/data/array.js @@ -0,0 +1,59 @@ +define([ + "./select", + "../utils" +], function (SelectAdapter, Utils) { + function ArrayAdapter ($element, options) { + this.data = options.options.data; + this.selection = []; + + ArrayAdapter.__super__.constructor.call(this, $element, options); + } + + Utils.Extend(ArrayAdapter, SelectAdapter); + + ArrayAdapter.prototype.select = function (data) { + var self = this; + + this.$element.find("option").each(function () { + var $option = $(this); + var option = self.item($option); + + if (option.id == data.id) { + $option.remove(); + } + }); + + var $option = this.option(data); + + this.$element.append($option); + + ArrayAdapter.__super__.select.call(this, data); + } + + ArrayAdapter.prototype.option = function (data) { + var $option = $(""); + + $option.text(data.text); + $option.val(data.id); + $option.data("data", data); + + return $option; + } + + ArrayAdapter.prototype.query = function (params, callback) { + var matches = []; + var self = this; + + $.each(this.data, function () { + var option = this; + + if (self.matches(params, option)) { + matches.push(option); + } + }); + + callback(matches); + } + + return ArrayAdapter; +}); diff --git a/src/js/select2/options.js b/src/js/select2/options.js index b0ce465d..0b25e462 100644 --- a/src/js/select2/options.js +++ b/src/js/select2/options.js @@ -3,7 +3,9 @@ define([ './results', './dropdown', './selection/single', - './selection/multiple' + './selection/multiple', + + './data/array' ], function (SelectData, ResultsList, Dropdown, SingleSelection, MultipleSelection) { function Options (options) { diff --git a/src/js/select2/selection/single.js b/src/js/select2/selection/single.js index 5e77e7c3..7d853763 100644 --- a/src/js/select2/selection/single.js +++ b/src/js/select2/selection/single.js @@ -26,6 +26,11 @@ define([ var self = this; this.$selection.on('mousedown', function (evt) { + // Only respond to left clicks + if (evt.which !== 1) { + return; + } + self.trigger("toggle", { originalEvent: evt });