Schlaus
Schlaus

Reputation: 19212

Using an object's method as an event handler, how do I remove it?

If I register an object's method as an event handler, I can't remove it. Am I missing something obvious, or can't it be done?

function Test() {
    
    document.body.addEventListener( 'click', this.handler.bind( this ), false );
    
}

Test.prototype.handler = function() {
    document.body.innerHTML += '.';
    document.body.removeEventListener( 'click', this.handler.bind( this ), false );
};

new Test();
body {
    border: 1px solid black;
    width: 100px;
    height: 100px;
    font-size: 30px;
}

Upvotes: 1

Views: 43

Answers (2)

Oriol
Oriol

Reputation: 288430

Each time you call bind, you will produce a different function:

func.bind(obj) === func.bind(obj); // false

Therefore, removeEventListener does not know which event listener to remove.

Instead, you should store the new function:

this.realHandler = this.handler.bind(this)

Then, you will be able to add or remove the this.realHandler event listener.

Upvotes: 3

Havvy
Havvy

Reputation: 1511

When you use Function.prototype.bind, you create a new function. Store your own reference to the function, and then use that to subscribe and unsubscribe.

var obj = {
    method: function () {
        return this.prop;
    },

    prop: true
};

var getProp = obj.method.bind(obj);
myHtmlElement.addEventListener("click", getProp, false);
myHtmlElement.removeEventListener("click", getProp, false);

Upvotes: 3

Related Questions