-
-
Save purplefox/2204406 to your computer and use it in GitHub Desktop.
I need a reference so I can unregister a handler from within a handler. otherwise would need to declare the handler first, put it in a variable and use that. | |
Wanna be able to do this with anon handlers | |
foo.registerHandler(myClosure = { | |
// Do something | |
// Now unregister handler | |
foo.unregisterHandler(myClosure) | |
}) |
IMHO it's really useful. This is exactly what I wanted Groovy to support....
Being able to unregister handlers from inside that handler is something you do all the time in event driven frameworks. Without something like this it becomes difficult.
@purplefox: understood yes. Although the trick with named arguments I showed earlier is IMHO a better and cleaner approach (works in classes, you're in control, familiar Groovy syntax, etc).
imho injecting a "self" reference into the closure would be simpler.
For named parameters, user won't always want to provide names and there can several other params too. Adding the param passing code in many places in vert.x (there are lots of places that take handlers) would be a pita.
Injecting self is still quite demanding, although easier. Just a thought: Any reason why Groovy doesn't inject a "self" (or set this) to point to the closure by default. I would have thought this would be a pretty useful thing.
Well, a long time ago, "this" pointed at the closure itself, and not at the surrounding class. But we changed that so that "this" had the same meaning as when you're inside any other Java block (think for example of for loops vs each loops).
And then we didn't introduce a "self", as it's only really needed when you do recursive algorithms with closures, which is not necessarily something you do that often in practice, and the workaround of first declaring the closure seemed to not have been too painful.
But which doesn't mean we can't or won't introduce that at some point.
getSelf()
on Closure for 2.0 would get my vote, but it does probably constitute a breaking change and undoubtedly there would be confusion between 'this' and 'self'. Anyway, this is a digression, sorry.
@pledbrook: it's like in while(line = readLine()) or in def a = b = 2, etc.
Although it's not necessarily something advised to do!