Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeBelt/6132133 to your computer and use it in GitHub Desktop.
Save codeBelt/6132133 to your computer and use it in GitHub Desktop.
StructureTS addEventListener and removeEventListener scope polyfill. Not fully tested in all browsers.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="polyfill.addEventListener.js"></script>
<script>
window.onload = function() {
(function() {
var Test = function() {
this.link = document.getElementById('js-link');
this.link.addEventListener('click', this.test, this, false);
this.image = document.getElementById('js-image');
this.image.addEventListener('click', this.test, this, false);
};
Test.prototype.test = function(event) {
event.preventDefault();
alert('click')
event.target.removeEventListener('click', this.test, this);
};
var test = new Test();
})();
}
</script>
</head>
<body>
<a href="javascript:void(0);" id="js-link">click</a>
<img id="js-image" width="100px" src="http://www.capca.ca/wp-content/uploads/Canada-small-87393222.jpg"/>
</body>
</html>
/**
* Polyfill for fix scoping and reference issues.
*/
(function(window, document)
{
// if (!Element.prototype.addEventListener) {
var _listeners = [];
function runListeners(event)
{
var list = _listeners[event.type];
if (list)
{
var i = list.length;
var listener;
while (--i > -1)
{
listener = list[i];
if (listener.e === this) {
listener.c.call(listener.s, event);
}
}
}
}
Element.prototype.addEventListener = function(type, callback, scope, useCapture, priority)
{
var list = _listeners[type];
if (list == null)
{
_listeners[type] = list = [];
}
var index = 0;
var listener;
var i = list.length;
while (--i > -1)
{
listener = list[i];
if (listener.c === callback && listener.s === scope && listener.e === this)
{
list.splice(i, 1);//If same callback and scope is found remove it. Then add the current one below.
}
else if (index === 0 && listener.pr < priority)
{
index = i + 1;
}
}
list.splice(index, 0, {c: callback, s: scope, e: this, pr: priority});
this["on" + type] = runListeners;
};
Element.prototype.removeEventListener = function(type, callback, scope, useCapture)
{
var list = _listeners[type];
if (list)
{
var i = list.length;
while (--i > -1)
{
if (list[i].c === callback && list[i].s === scope && list[i].e === this)
{
list.splice(i, 1);
break;
}
}
}
};
// }
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment