Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function that allows us to remove the event listeners #513

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions mousetrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,23 @@
object.attachEvent('on' + type, callback);
}

/**
* cross browser remove event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _removeEvent(object, type, callback) {
if (object.removeEventListener) {
object.removeEventListener(type, callback, false);
return;
}

object.detachEvent('on' + type, callback);
}

/**
* takes the event and returns the key character
*
Expand Down Expand Up @@ -891,6 +908,19 @@
_addEvent(targetElement, 'keyup', _handleKeyEvent);
}

/**
* Removes the event listeners. This is useful if the element is
* being removed and to prevent memory leaks.
*
* @returns void
*/
Mousetrap.prototype.removeListeners = function() {
_removeEvent(targetElement, 'keypress', _handleKeyEvent);
_removeEvent(targetElement, 'keydown', _handleKeyEvent);
_removeEvent(targetElement, 'keyup', _handleKeyEvent);
};


/**
* binds an event to mousetrap
*
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mousetrap",
"version": "1.6.5",
"version": "1.6.6",
"description": "Simple library for handling keyboard shortcuts",
"main": "mousetrap.js",
"directories": {
Expand Down