Matoy Matoy - 10 months ago 54
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){

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){
var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
var top = + (e.pageY - my_dragging.pageY0);
.offset({top: top, left: left});
function handle_mouseup(e){
.off('mousemove', handle_dragging)
.off('mouseup', handle_mouseup);
console.log("drag was done!!");
console.log("click was done!!");

.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
//set the mousedwon to the div

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..


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??


Answer Source

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);