The addEventListener function is a method of the Element class. One way is to make CustomObject inherit from Element as follows:
CustomObject.prototype = Element.prototype;
The problem is that the Element class may have different implementations among different browsers. So, for example, dismissal can be difficult (see this post ).
Therefore, I advise you to do it yourself. It is not difficult, try something like this:
var CustomObject = function () { var _this = this; _this.events = {}; _this.addEventListener = function(name, handler) { if (_this.events.hasOwnProperty(name)) _this.events[name].push(handler); else _this.events[name] = [handler]; }; _this.removeEventListener = function(name, handler) { if (!_this.events.hasOwnProperty(name)) return; var index = _this.events[name].indexOf(handler); if (index != -1) _this.events[name].splice(index, 1); }; _this.fireEvent = function(name, args) { if (!_this.events.hasOwnProperty(name)) return; if (!args || !args.length) args = []; var evs = _this.events[name], l = evs.length; for (var i = 0; i < l; i++) { evs[i].apply(null, args); } }; }
Now using it is as simple as:
var co = new CustomObject(); co.addEventListener('textChange', function(name) { console.log(name); }); co.fireEvent('textChange', ['test']);
This is a basic solution. You can change it, but I think you should understand this idea.
freakish Jun 11 '12 at 11:17 2012-06-11 11:17
source share