Reputation: 393
EDIT Solved by using jQuery's .on()
method and removing the event via .off()
and .unbind()
.
I have a simple Drag and Drop upload system. Everything works fine until I reinitialize my functions. Problem is that after my second initialization events are still binded after I tried to unbind them before.
I would like to keep the way I add event listeners, just want to remove the old before adding new.
Check jsfiddle for example (try to drag and drop some file inside the black box). You can see that the console.log()
is runned twice after reinitialization.
function init() {
console.log('init')
var dropZone = $('.dropZone');
var dropZoneEvent = dropZone.get(0);
function dragEnter(ev) {
ev.preventDefault();
console.log('drag enter');
}
function dragOver(ev) {
ev.preventDefault();
}
function dragLeave(ev) {
ev.preventDefault();
console.log('drag leave');
}
function drop(ev) {
ev.preventDefault();
console.log("drop");
}
dropZoneEvent.removeEventListener('dragenter', dragEnter, false);
dropZoneEvent.removeEventListener('dragover', dragOver, false);
dropZoneEvent.removeEventListener('dragleave', dragLeave, false);
dropZoneEvent.removeEventListener('drop', drop, false);
dropZoneEvent.addEventListener('dragenter', dragEnter, false);
dropZoneEvent.addEventListener('dragover', dragOver, false);
dropZoneEvent.addEventListener('dragleave', dragLeave, false);
dropZoneEvent.addEventListener('drop', drop, false);
}
init();
$(document).on('click', '.reinit', function() {
init();
});
.dropZone {
width: 200px;
height: 80px;
background: black;
}
.reinit{
width: 200px;
height: 40px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropZone"></div>
<div class="reinit">Click me to reinit</div>
Upvotes: 0
Views: 980
Reputation: 135
This is because your event functions are in the init
inner scope. And every time you run init
these functions are not pointed to the same reference.
Get these functions out of the init
and put them in global scope and it will work fine.
Upvotes: 1