I have searched for similar issues and found #35 and #3390 which is quite similar but was abandoned by the reporter. So instead of posting there, created a new ticket per @kevin-brown suggestion. I didn't get a chance to check with the latest master, but a if fixed, a pointer will help.
HTML:
<div id="test-list">
<div class="input select">
<label for="list">Product</label>
<select id="list" placeholder="Select" tabindex="0">
<option value=""></option>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
</div>
</div>
<button type="button" id="toggle">Toggle</button>
Javascript:
function createDestroy() {
if(!$('#list').hasClass('select2-hidden-accessible')) {
$('#list').select2({
placeholder: "--Select--",
width: "100%",
allowClear: true,
}).on('change', function() {
var val = $(this).val();
if(val) {
alert('changed');
}
});
} else {
$('#list').select2('destroy');
}
}
$('#toggle').on('click', function(e) {
createDestroy();
});
Check this jsFiddle, steps included there.
When I follow those steps, I see that the change event is still triggered after destroying select2, and when i initialize select2 on that element again, change event is triggered twice.
I was expecting the events attached to select2 to be unbind on destroy. That won't trigger a change when there is no select2 and will trigger only once no matter how many times i destroy/re-init select2.
Browsers
Libraries
This is not a Select2 bug, but a general expectation of how events work with jQuery plugins.
I was expecting the events attached to select2 to be unbind on destroy.
Select2 will only destroy event handlers that it creates when it is destroyed. It's very common for people to reinitialize Select2, and we wouldn't want to overstep our boundaries by removing things that we did not create.
You can manually unbind the change event by calling
$mySelect.off('change');
right after you destroy Select2.
Reopening this issue because we need to document this behavior.
Looks like this was done, but I never closed this issue: https://select2.org/programmatic-control/methods#event-unbinding
Most helpful comment
This is not a Select2 bug, but a general expectation of how events work with jQuery plugins.
Select2 will only destroy event handlers that it creates when it is destroyed. It's very common for people to reinitialize Select2, and we wouldn't want to overstep our boundaries by removing things that we did not create.
You can manually unbind the
changeevent by callingright after you destroy Select2.