KKY
KKY

Reputation: 13

How to unbind document keypress event with anonymous function

This is page's code. I can't modify this.

var Example = {};

Example.create = function() {
    var obj = new Example.object();
    return obj;
}

Example.object = function(){
    this.initialize = initialize;
    function initialize() {
        window.addEventListener('load', activate);
    }
    function activate() {
        document.addEventListener('keypress', keyPressed);
    }
    function keyPressed(e) {
        alert("Hello!");
    }
};

Example.defaultObject = Example.create();
Example.defaultObject.initialize();

I have tried many things...

document.onkeypress = null;
document.keypress = null;
document.removeEventListener('keypress');
$(document).unbind('keypress');
$(document).off("keypress");
$("*").unbind('keypress');
$(document).bind('keypress', function(e) { e.stopPropagation(); });

but all failed.

How can I unbind event of document keypress?

Upvotes: 0

Views: 2262

Answers (2)

Venkat.R
Venkat.R

Reputation: 7746

Root cause of the issue is removeEventListener method. This method expect second parameter which is listener method

document.removeEventListener('keypress', Example.defaultObject.keyPressed);

Here you go for Solution on your problem.

var Example = {};

Example.create = function() {
    var obj = new Example.object();
    return obj;
}

Example.object = function(){
    this.initialize = initialize;
    function initialize() {
        window.addEventListener('load', activate);
        document.getElementById('disable').addEventListener('click', deActivate);
    }
    function activate() {
        document.addEventListener('keypress', keyPressed);
    }
    function deActivate() {
        document.removeEventListener('keypress', keyPressed);
        document.querySelector('h1').innerHTML = 'Page Key Press Listener Removed';
    }
    function keyPressed(e) {
        alert("Hello!");
    }
};

Example.defaultObject = Example.create();
Example.defaultObject.initialize();
<body>
  <h1>Page has Key Press Listener</h1>
  <input id="disable" type="button" value="deactivate">
  </body>

Upvotes: 0

CoderPi
CoderPi

Reputation: 13211

You have to pass the listener to remove it: (a variable pointing the function aka the function name)

document.removeEventListener('keypress',  keyPressed);

https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener

You will have to save it somewhere to remove it later

Upvotes: 1

Related Questions