Matoy Matoy - 17 days ago 5
Javascript Question

JQuery + AngularJS: mousedown event is being called multiple times

I have a single page application in angular.

I cannot use jquery draggable method so I wrote one myself -

// here I am setting the drag event to a div
var enableDrag = function(id){
$('#'+id).on('mousedown',handleMousedown);
}

var handleMousedown =function (e){
window.my_dragging = {};
my_dragging.pageX0 = e.pageX;
my_dragging.pageY0 = e.pageY;
my_dragging.elem = this;
my_dragging.offset0 = $(this).offset();
var isDragAction=false;
function handle_dragging(e){
isDragAction=true;
var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
$(my_dragging.elem)
.offset({top: top, left: left});
}
function handle_mouseup(e){
$('body')
.off('mousemove', handle_dragging)
.off('mouseup', handle_mouseup);
if(isDragAction){
console.log("drag was done!!");
}
else{
console.log("click was done!!");
}

}
$('body')
.on('mouseup', handle_mouseup)
.on('mousemove', handle_dragging);
}


And in my method I am calling this like this:

//set off the last mousedwon to the div
$("someDiv").off('mousedown',handleMousedown);
//set the mousedwon to the div
enableDrag("someDiv");


I need to call it each time the method is being called instead of just one time because of how my angular app is working.

the dragging works fine

problem is that each time the method is being called - a new event is being added in addition to the previous events..

meaning:

1st method is being called - dragging will print to the console:

"drag was done!!"


2nd method is being called, on a single drag:

"drag was done!!"
"drag was done!!"


n time method is being called, on a single drag:

"drag was done!!"
"drag was done!!"
.
.
.
"drag was done!!"


what is accumulating the events or causing this multiple prints??

Thanks

Answer

Try ensuring the event is set only once by removing it before setting it, rather than doing it separately. Not sure this is the problem because I haven't tested it in your example.

var enableDrag = function(id) {
  $('#'+id).off('mousedown').on('mousedown', handleMousedown);
}