It appears that if you want to remove an event listener that was added via
command(), you have to hold on to a bunch of references so that you can later pass them to
off(). Oftentimes, an event handler is an anonymous function, so if you want to remove the handler later, you can no longer declare it an anonymous way, which is annoying. It also requires creating an object with at least two fields (
handler), which you have to pass around to whoever is ultimately responsible for removing the listener. This also means that your
handler is potentially exposed to much more code than it should be.
By comparison, consider goog.events.listen() from the Closure Library. It takes an equivalent set of arguments that
on() does, but it returns an opaque object to represent the registration of your listener:
goog.events.Key (this is just a type alias for
number, so it is very cheap). The listener can be removed by goog.events.unlistenByKey(key), which takes the
goog.events.Key object returned by
goog.events.listen(). This addresses all of the shortcomings of the jQuery approach mentioned above.
(1) Is there a better way to do this in jQuery/SpacePen today?
(2) Could an analogous abstraction be introduced to SpacePen?