views:

46

answers:

2

Hi,

I often need to create single events that are not needed after they have run once. The way I do is something like:

A.prototype.someMethod = function () {
    var me = this;
    this.onWindowMouseUpFunction = function () {
        me.onWindowMouseUp.apply(me, arguments);
    };
    window.addEventListener('mouseup', this.onWindowMouseUpFunction, false);
}

A.prototype.onWindowMouseUp = function () {
    window.removeEventListener('mouseup', this.onWindowMouseUpFunction, false);
}

However, since the event logic is split into two methods and I cannot use anonymous functions and instead have to assign the function to a variable, I have begun to think that there must be a better way of doing this, right?

A: 

Simply do this:

A.prototype.someMethod = function () {
    function onMouseUp() {
        // do stuff ...
        // then remove event listener      
        window.removeEventListener('mouseup', onMouseUp, false);
    }
    window.addEventListener('mouseup', onMouseUp, false);
}

There's less typing involved and your event listener becomes private.

galambalazs
+1  A: 

I think your best shot is to create a wrapper function that does all this automatically.

Something like

function addOneTimeEventListener(objToListenOn, eventtype, callbackfunction){
 var callThenRemove = function() {
   callbackfunction();
   objToListenOn.removeEventListener(eventtype, callThenRemove, false);   
 };
 objToListenOn.addEventListener(eventtype, callThenRemove, false);
};

Usage

addOneTimeEventListener(window, "mouseup", function(){/*tada, anonymus function*/});
snowandice