Last active
November 16, 2015 16:07
-
-
Save codeBelt/7e7a9da1d85fc967a0d9 to your computer and use it in GitHub Desktop.
Overriding addEventListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A bind polyfill for browsers that don't support the bind method. | |
*/ | |
if (!Function.prototype.bind) { | |
Function.prototype.bind = function (oThis) { | |
if (typeof this !== 'function') { | |
// closest thing possible to the ECMAScript 5 internal IsCallable function | |
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); | |
} | |
var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { | |
}, fBound = function () { | |
return fToBind.apply(this instanceof fNOP && oThis | |
? this | |
: oThis, aArgs.concat(Array.prototype.slice.call(arguments))); | |
}; | |
fNOP.prototype = this.prototype; | |
fBound.prototype = new fNOP(); | |
return fBound; | |
}; | |
} | |
/** | |
* Generates a hash string from the string being passed in. In this case it is a function that is casted as string value. | |
* | |
* @param str | |
* @returns {String} | |
*/ | |
var hashCode = function (str) { | |
str = String(str); | |
// http://erlycoder.com/49/javascript-hash-functions-to-convert-string-into-integer-hash- | |
var character; | |
var hash = null; | |
var strLength = str.length; | |
if (strLength == 0) | |
return hash; | |
for (var i = 0; i < strLength; i++) { | |
character = str.charCodeAt(i); | |
hash = ((hash << 5) - hash) + character; | |
hash = hash & hash; // Convert to 32bit integer | |
} | |
return String(Math.abs(hash)); | |
}; | |
var add = EventTarget.prototype.addEventListener; | |
EventTarget.prototype.addEventListener = function(type, fn, scope, capture) { | |
if (typeof scope === 'boolean' || scope == null) { | |
this.f = add; | |
this.f(type, fn, scope); | |
} else { | |
this._scope = scope; | |
this._scope._handlerMap = this._scope._handlerMap || {}; | |
this._handler = this._scope._handlerMap[hashCode(fn)] = fn.bind(this._scope); | |
this.f = add; | |
this.f(type, this._handler, capture); | |
} | |
}; | |
var remove = EventTarget.prototype.removeEventListener; | |
EventTarget.prototype.removeEventListener = function(type, fn, scope, capture) { | |
if (typeof scope === 'boolean' || scope == null) { | |
this.f = remove; | |
this.f(type, fn, scope); | |
} else { | |
this._scope = scope; | |
this._scope._handlerMap = this._scope._handlerMap || {}; | |
this._handler = this._scope._handlerMap[hashCode(fn)]; | |
this.f = remove; | |
this.f(type, this._handler, capture); | |
this._scope._handlerMap[hashCode(fn)] = null; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment