Re: addEventListener naming

On Sun, 13 Sep 2009 00:13:32 -0400, Michael A. Puls II  
<shadow2531@gmail.com> wrote:

> Jonas Sicking <jonas@sicking.cc> wrote:
>> 2. If the long name is a significant problem, then it can easily be
>> worked around in JS by using prototypes.
>
> What's the proper way to do that so that it feels close to like it was  
> implemented natively?
>
> Would the following be close?
>
> window.listen = Node.prototype.listen = function(type, func, capt) {
>      if (typeof capt !== "bool") capt = false;
>      this.addEventListener(type, func, capt);
> };
> window.unlisten = Node.prototype.unlisten = function(type, func, capt) {
>      if (typeof capt !== "bool") capt = false;
>      this.removeEventListener(type, func, capt);
> };
> window.listenOnce = Node.prototype.listenOnce = function(type, func,  
> capt) {
>      function wrapper(e) {
>          func.apply(this, [e]);
>          this.unlisten(type, wrapper, capt);
>      }
>      this.listen(type, wrapper, capt);
> };
>
> If so, even though that's not much code (especially if you don't need  
> the 3rd), I don't know if I'd bother.
>
> If browsers implement listen() though, I would prefer it over  
> addEventListener, as long as I didn't have to do if (foo.listen) {} else  
> if(foo.addEventListener) {} everywhere.

I guess it'd be more like:

EventTarget.prototype.listen = function(type, func, capt) {
     if (typeof capt !== "boolean") capt = false;
     this.addEventListener(type, func, capt);
};
EventTarget.prototype.unlisten = function(type, func, capt) {
     if (typeof capt !== "boolean") capt = false;
     this.removeEventListener(type, func, capt);
};
EventTarget.prototype.listenOnce = function(type, func, capt) {
     if (typeof capt !== "boolean") capt = false;
     function wrapper(e) {
         func.apply(this, [e]);
         this.unlisten(type, wrapper, capt);
     }
     this.listen(type, wrapper, capt);
};

or something, so that all objects that implement EventTarget (like window  
and xhr etc.) will have the functions.

But, only Firefox exposes window.EventTarget and it doesn't even work  
because things are not inherited down to all the objects properly or  
something.

So, I guess using prototypes to add the shorthand functions wouldn't work  
unless you do it part-way on just the actual objects you want to use.

-- 
Michael

Received on Sunday, 13 September 2009 12:21:11 UTC