Hacker News new | comments | show | ask | jobs | submit login
Gator.js - simple event delegation in ~800 bytes (craig.is)
28 points by craigc 1784 days ago | hide | past | web | 7 comments | favorite

Why is there a Gator function when the only interface is `Gator(x).on(e, s, c)` and `Gator(x).off(e, s, c)`? Why not `Gator.on(x, e, s, c)` and rely on the caller to do partial function application (e.g. with `Function.prototype.bind`)? This seems like unnecessary memory bloat[1].

[1] https://github.com/ccampbell/gator/blob/0c8fafad45202c018706...

Thanks for the comment. I considered that, but I was thinking it makes things a little cleaner/easier to maintain by using Gator objects. Only one object instance is created per element. Also it allows for chaining methods.

I see. Still, your approach leaks memory as it maintains references to nodes which may otherwise be GC'able. Have you considered `WeakMap` for caching (where supported)?

That's a good point. I probably will add some sort of destroy method. I figure in most cases with delegation you are referencing an element that is not likely to be removed (such as document), but I probably should add a way to clean up stale objects.

As for WeakMap, I wasn't even aware of that, looks awesome.

> Only one object instance is created per element

I think the point may be "Gator.on()" wouldn't need instances of anything allocated.

But then you lose chaining.

Probably for "chaining", like all the cool libraries do now.

      .on(x, e1, s1, c1)
      .on(x, e2, s2, c2)
Or is chaining desired after partial application (meaning `x` is chained)?

    var onX = chainFn(Gator.on, x);
      (e1, s1, c1)
      (e2, s2, c2)
It seems that a library can provide chaining if needed.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact