{}Caveats of {}
In JavaScript {} is notoften used as a pure empty map, so one can't use it in with user provided values being object property names. This can be a manner of lookupObj[key] and stay saferecipe for disaster.
To overcome See this you've used hasOwnProperty methodparticular piece of code, but check this onethat results in error:
The error you'llwe'll get comes from addHandler function that uses in operator.
When addHandler is called with event "toString" it checks if "toString" in this.eventHandlers.
It finds one in Object.prototype since {} inherits from it. From now on we are in trouble.
If youwe replace the in with hasOwnProperty call you'llwe'll still be in trouble when someone will desidedesides that hasOwnProperty is a good name for an event:
All yourAfter that all this.eventHandlers.hasOwnProperty expressions will evaluate to array of handlers. See this:
To safely call hasOwnProperty on object with user provided property names you canwe should use function from Object.prototype directly:
Actually same stands for any standard method we want to call.
once method has one particular fail case when the same event is emitted directly from the event handler:
var handler = function() { /* handler code */ };
ev.on("foo", handler);
ev.off("foo", handler);
You are comparing functions by their string representation:
callback.toString() == this.eventHandlers[event][index].callback.toString()
You are comparing functions by their string representation. Actually, you can compare functions directly:
- I don't see any point in
if (handler.hasOwnProperty('once')), considerif (handler.once)instead. indexis a long name for a loop variable, how about plain oldi?for (var i in arr)form is for iteration over object property names where iteration order is not guranteed. To iterate over arrays, usefor (var i = 0; i < arr.length; i++)instead.