Issue
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.
The problem is that each time the method is being called – a new event is being added in addition to the previous events..
Meaning:
First method is being called – dragging will print to the console:
"drag was done!!"
Second method is being called, on a single drag:
"drag was done!!"
"drag was done!!"
In 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?
Solution
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);
}
Answered By – Jared Insel
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0