Skip to content

Commit 6d0ecbc

Browse files
Nadeem Afanaalexweissman
authored andcommitted
Exposes select2 instance via .data('select2')
1 parent 5424333 commit 6d0ecbc

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

src/js/select2/core.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,9 @@ define([
8484
this._syncAttributes();
8585

8686
Utils.StoreData($element[0], 'select2', this);
87+
88+
// Ensure backwards compatibility with $element.data('select2').
89+
$element.data('select2', this);
8790
};
8891

8992
Utils.Extend(Select2, Utils.Observable);
@@ -579,6 +582,7 @@ define([
579582
this.$element.removeClass('select2-hidden-accessible');
580583
this.$element.attr('aria-hidden', 'false');
581584
Utils.RemoveData(this.$element[0]);
585+
this.$element.removeData('select2');
582586

583587
this.dataAdapter.destroy();
584588
this.selection.destroy();

tests/integration/jquery-calls.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
module('select2(val)');
22

3+
var Utils = require('select2/utils');
4+
35
test('multiple elements with arguments works', function (assert) {
46
var $ = require('jquery');
57
require('jquery.select2');
@@ -56,4 +58,41 @@ test('initializes when jQuery $.data contains' +
5658
'3',
5759
'The option value should be pulled correctly'
5860
);
61+
});
62+
63+
test('$element.data returns instance and options correctly',
64+
function (assert) {
65+
var $ = require('jquery');
66+
require('jquery.select2');
67+
68+
var $select = $(
69+
'<select>' +
70+
'<option value="1">One</option>' +
71+
'<option value="2">Two</option>' +
72+
'<option value="3" selected>Three</option>' +
73+
'</select>'
74+
);
75+
76+
// Initialize.
77+
$select.select2({maximumSelectionLength: 2, multiple: true});
78+
79+
assert.equal(
80+
$select.val(),
81+
'3',
82+
'Only 1 option should be pulled.'
83+
);
84+
85+
// Try to resolve instance via .data('select2').
86+
var $instance = $select.data('select2');
87+
assert.ok($instance);
88+
assert.ok($instance.options);
89+
90+
// Ensure $select.data('select2') is the same instance
91+
// created by .select2()
92+
assert.equal($instance, Utils.GetData($instance.$element[0],
93+
'select2'));
94+
95+
// Ensure initialized property matches.
96+
assert.equal($instance.options.options.maximumSelectionLength,
97+
2);
5998
});

0 commit comments

Comments
 (0)