Select2 Bug: No unbind events on Destroy
Description is included within the fiddle.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<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>
<ol class="info">
<li>Select an item in list; no alert should come</li>
<li>Click on toggle button; list should convert to Select2</li>
<li>Select an item in list; alert should appear</li>
<li>Click on toggle button; list should convert back to html select</li>
<li>Select an item in list; no alert should come because as expected, all the bound events should unbind on destroy. <b>However, an alert still appears</b></li>
</ol>
<footer>
<p>
Created this fiddle to demonstrate the bug that doesn't unbind events on destroy.
</p>
</footer>
CSS
footer {
position: fixed;
bottom: 0;
padding: 10px;
background-color: #123456;
color: #fedcba;
width: 100%;
}
.info {
background-color: #abcdef;
}
.info>li {
padding: 10px;
}
JavaScript
function createDestroy() {
if(!$('#list').hasClass('select2-hidden-accessible')) {
$('#list').select2({
placeholder: "--Select--",
width: "100%",
allowClear: true,
}).on('keyup', function() {
var val = $(this).val();
if(val) {
alert('changed');
}
});
} else {
$('#list').select2('destroy');
}
}
$('#toggle').on('click', function(e) {
createDestroy();
});