I was working on a cross-browser event handling system. And I asked some developers to review my code. One of the developers said that my implementation is based on callbacks and not real events. What is the difference?
I have provided the source code of my implementation below for your convenience (and also as a gist). So far, I haven't found any problems with it. It works fine with all browsers that I tested with.
I'm sorry for the bad description of the problem, I am not familiar with that pure-event part.
var evento = (function (window) { var win = window , doc = win.document , _handlers = {} , addEvent , removeEvent , triggerEvent; addEvent = (function () { if (typeof doc.addEventListener === "function") { return function (el, evt, fn) { el.addEventListener(evt, fn, false); _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt].push(fn); }; } else if (typeof doc.attachEvent === "function") { return function (el, evt, fn) { el.attachEvent(evt, fn); _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt].push(fn); }; } else { return function (el, evt, fn) { el["on" + evt] = fn; _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt].push(fn); }; } }()); // removeEvent removeEvent = (function () { if (typeof doc.removeEventListener === "function") { return function (el, evt, fn) { el.removeEventListener(evt, fn, false); Helio.each(_handlers[el][evt], function (fun) { if (fun === fn) { _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt][_handlers[el][evt].indexOf(fun)] = undefined; } }); }; } else if (typeof doc.detachEvent === "function") { return function (el, evt, fn) { el.detachEvent(evt, fn); Helio.each(_handlers[el][evt], function (fun) { if (fun === fn) { _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt][_handlers[el][evt].indexOf(fun)] = undefined; } }); }; } else { return function (el, evt, fn) { el["on" + evt] = undefined; Helio.each(_handlers[el][evt], function (fun) { if (fun === fn) { _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; _handlers[el][evt][_handlers[el][evt].indexOf(fun)] = undefined; } }); }; } }()); // triggerEvent triggerEvent = function (el, evt) { _handlers[el] = _handlers[el] || {}; _handlers[el][evt] = _handlers[el][evt] || []; for (var _i = 0, _l = _handlers[el][evt].length; _i < _l; _i += 1) { _handlers[el][evt][_i](); } }; return { add: addEvent, remove: removeEvent, trigger: triggerEvent, _handlers: _handlers }; }(this));
typeof doc.attachEventreturnsobject(where implemented) so those forks of your code will never be executed. Some host objects returnunknown. Host objects are not required to conform to all details of ECMA-262, so you should not rely on them doing so.doc.attachEventas inelse if (doc.attachEvent) { // }would be enough?