Tower
Tower

Reputation: 102765

How to handle single JavaScript events intuitively?

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?

Upvotes: 1

Views: 216

Answers (2)

gblazex
gblazex

Reputation: 50101

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.

Upvotes: 0

snowandice
snowandice

Reputation: 46

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*/});

Upvotes: 2

Related Questions