Stop Observing Events with JS Prototype not working with .bind(this)

Posted by PeterBelm on Stack Overflow See other posts from Stack Overflow or by PeterBelm
Published on 2010-04-02T16:20:54Z Indexed on 2010/04/02 16:23 UTC
Read the original article Hit count: 229

I'm working on a Javascript class based on the Prototype library. This class needs to observe an event to perform a drag operation (the current drag-drop controls aren't right for this situation), but I'm having problems making it stop observing the events.

Here's a sample that causes this problem:

var TestClass = Class.create({
    initialize: function(element) {
        this.element = element;
        Event.observe(element, 'mousedown', function() {
            Event.observe(window, 'mousemove', this.updateDrag.bind(this));
            Event.observe(window, 'mouseup', this.stopDrag.bind(this));
        });
    },
    updateDrag: function(event) {
        var x = Event.pointerX(event);
        var y = Event.pointerY(event);
        this.element.style.top = y + 'px';
        this.element.style.left = x + 'px';
    },
    stopDrag: function(event) {
        console.log("stopping drag");
        Event.stopObserving(window, 'mousemove', this.updateDrag.bind(this));
        Event.stopObserving(window, 'mouseup', this.stopDrag.bind(this));
    }
});

Without .bind(this) then this.element is undefined, but with it the events don't stop being observed (the console output does occur though).

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events