Re: Better event listeners

On Wed, Jan 9, 2013 at 8:35 PM, Jonas Sicking <jonas@sicking.cc> wrote:

> If you do that, the "this" object when clickhandler is called won't be
> |object| but rather |foo|. Instead people end up doing
>
> foo.addEventListener("click", object.clickhandler.bind(object));
>
> which is pretty verbose.
>

I don't think this is harmfully verbose.  It's not nearly as nice as
Python's mechanism (which automatically does the bind for you), but it's
not a big deal--not enough to justify a whole new distinct API, at least.

It would be nice if it was possible to automatically register a set of
> functions on an object to as listener for a set of events. And that
> the functions were dispatched such that the 'this' object was the
> "correct" object. In other words, that you could actually use OOP
> style for your code. Especially since a lot of large JS codebases use
> OOP style to a large extent. Which shouldn't be surprising given that
> JS is, you know, a OOP based language :)
>

I don't think this is a problem that should be solved at this level, since
it applies to every callback-based API.  It's the same as having to say
"setInterval(this.update.bind(this), 1000)".  If there's to be any solution
for this (and I'm not sure there needs to be), it should be at the language
level, not whack-a-moled at the API level.

But I've really never found saying ".bind(this)" to be a burden.  It's a
minor annoyance at worst.

(I also don't think I agree that passing in an object implementing a bunch
of event listeners as methods is any more "OOP style" than passing in a
function, FWIW.)

MyClass.prototype = {
>   onclick: function(event) { ... },
>   ondblclick: function(event) { ... },
>   somehelperfunction: function(x) { ... }
> }
>

In general I don't like these, partly due to the above, and partly because
I don't see any real benefit to justify adding such another distinct way of
doing the same task, which is a big cost.  It also seems fairly complex and
unlike anything else on the platform that I know of, and makes everyone
learn another API (a greater cost than all the times I've typed
".bind(this)" in my career combined).

-- 
Glenn Maynard

Received on Thursday, 10 January 2013 03:40:50 UTC