فهرست منبع

Adding container support #3222

Fixes issue #3222
Now templateSelection can have access to the parent container so that
classes can be added for styling
Stretch 10 سال پیش
والد
کامیت
13cead0bd0
2فایلهای تغییر یافته به همراه38 افزوده شده و 3 حذف شده
  1. 3 3
      src/js/select2/selection/multiple.js
  2. 35 0
      tests/selection/multiple-tests.js

+ 3 - 3
src/js/select2/selection/multiple.js

@@ -50,11 +50,11 @@ define([
     this.$selection.find('.select2-selection__rendered').empty();
   };
 
-  MultipleSelection.prototype.display = function (data) {
+  MultipleSelection.prototype.display = function (data, container) {
     var template = this.options.get('templateSelection');
     var escapeMarkup = this.options.get('escapeMarkup');
 
-    return escapeMarkup(template(data));
+    return escapeMarkup(template(data, container));
   };
 
   MultipleSelection.prototype.selectionContainer = function () {
@@ -81,8 +81,8 @@ define([
     for (var d = 0; d < data.length; d++) {
       var selection = data[d];
 
-      var formatted = this.display(selection);
       var $selection = this.selectionContainer();
+      var formatted = this.display(selection, $selection);
 
       $selection.append(formatted);
       $selection.prop('title', selection.title || selection.text);

+ 35 - 0
tests/selection/multiple-tests.js

@@ -33,6 +33,41 @@ test('display uses templateSelection', function (assert) {
   assert.equal(out, 'test');
 });
 
+test('templateSelection can addClass', function (assert) {
+  var called = false, found = false;
+
+  var templateOptions = new Options({
+    templateSelection: function (data, container) {
+      called = true;
+      container.addClass('testclass');
+      return data.text;
+    }
+  });
+
+  var selection = new MultipleSelection(
+    $('#qunit-fixture .multiple'),
+    templateOptions
+  );
+
+  var $container = selection.selectionContainer();
+  
+  var out = selection.display({
+    text: 'test'
+  }, $container);
+
+  for (var i = 0; i < $container[0].classList.length; i += 1) {
+    if ($container[0].classList[i] === 'testclass') {
+      found = true;
+    }
+  }
+  
+  assert.ok(called);
+
+  assert.equal(out, 'test');
+  
+  assert.ok(called);
+});
+
 test('empty update clears the selection', function (assert) {
   var selection = new MultipleSelection(
     $('#qunit-fixture .multiple'),