On Sat, Mar 26, 2011 at 11:51 AM, BlessYAHU <[email protected]> wrote:
> I know one can use deferreds and promises when doing ajax calls, but
> can these be used for custom events?
Sure, why not? It's not *quite* as free wheeling as an event emitter style,
but if you can normalize your events into a stream-like metaphor ("data"
chunks, "error", "complete") you can go a long way with asynchronous
*forEachable
*streams. These are objects with a forEach method (as in
Array.prototype.forEach) that return a promise that *eventually* resolves to
undefined to signal completion (in this case I guess this could represent
"listener" removal but isn't really necessary).
So per usual you would provide a *handler* function to forEach that would be
provided the event object as the first arg and you would do stuff. If an
exception occurs that causes the emitter to stop emitting events, the
promise originally returned by forEach would be rejected and the errback, if
provided, would be called. This can model a wide range of problems, but
admittedly, it's a little tortured when you can just use events. Still, it's
a neat approach that hides the event loop and forces a consistency to your
events streams. This allows you to reframe them in interesting ways and
affords you some functional niceties [1]. Your code comes out looking pretty
clean.
> Is pubsub the best way to have
> decoupled components talk to each other?
>
That depends on your use case and your tastes. I tend to fancy cleaner
modeled query subscriptions (something like this [2]) over the anarchy that
pubsub can turn into.
>
> Only thing I think is missing from pubsub is having a way to know
> which event a component subscribes/publishes.
>
That's what the docs are for I guess. Still, I much prefer the
self-documenting (and discoverable) nature of resource modeling.
[1] https://github.com/kriszyp/promised-io/blob/master/lib/lazy-array.js
[2]
http://dojotoolkit.org/reference-guide/dojo/store/Observable.html#dojo-store-observable
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]