Justin Meltzer
Justin Meltzer

Reputation: 13558

A misunderstanding of how this javascript is working

I bind an event to a channel on the client side that waits for a message from the server and triggers the anonymous function in a callback, passing the message data in the thing parameter.

channel.bind('coordinates_sent', function(thing) {
     var x = thing.left;
     var y = thing.top;

     $(window).scroll(function(){
           alert(x + " " + y);
     });

     alert(x + " " + y);
});

The alert message outside of the scroll method works as expected. It alerts the new x and y coordinates of the data sent from the server right when the new message arrives.

However, the alert message inside the scroll message behaves differently from how I would expect it to. If one message has been sent to the event listener, then the alert correctly displays the x and y coordinates from that message every time I scroll. However, if another message comes in, the alert displays first the original x and y coordinates from the first message, and then a separate alert displays the x and y coordinates from the most recent message.

I'm having trouble understanding why this is happening.

Upvotes: 2

Views: 88

Answers (2)

Eduard
Eduard

Reputation: 3216

Jquery .bind() method registers handlers but doesnt unbound them. Try to use .one() instead, see here.

Upvotes: 0

icktoofay
icktoofay

Reputation: 129139

Whenever you're receiving a message from the server, you're attaching a new scroll event handler. When you attach an event listener, existing listeners are not removed. When the user scrolls, all attached event handlers are executed.

To fix this, move the part where it attaches a scroll event outside of the event handler for a message being received by the server:

var x, y;
channel.bind('coordinates_sent', function(thing) {
    x = thing.left;
    y = thing.top;

    alert(x + " " + y);
});
$(window).scroll(function(){
    alert(x + " " + y);
});

Upvotes: 1

Related Questions