Tuesday, February 14, 2012

Event Listeners

Event Listeners

Get up to speed first:
Part 1: http://randomgoo.blogspot.com/2012/02/release-event-hub-web-30-introduction.html
Part 2: http://randomgoo.blogspot.com/2012/02/events.html

Quick recap - Web 3.0 is two-way asynchronous programming - events on the way out and another event or a callback on the way back.

There is no special syntax or language features required to listen for and respond to events.  So listen up!

hub.on('user:add', function(params, callback) {
    var user = params.user
          , pass = params.pass
    ;


    // Do something interesting (probably throw more events to
    //     save off to the DB) & when done if no error:
    callback(null, { success: true });
});

That's really it, attach a function to an event - the first parameter will be an object and the second will be a callback.  Both parameters are optional.

Note these examples use Javascript but THAT OF COURSE IS NOT REQUIRED!

Not all events require a response!  It's all about the documentation and expectation - event listeners MUST supply some sort of documentation to emitters:

/**
 * @method user:add handler
 * @param user username
 * @param pass password
 * @param callback required - response will contain 'success' 
 *    true or false
 */

Something like that - exactly as you would document a method-based API.  This handler can just as easily throw a 'user:Added' event instead of a callback:

hub.fire('user:Added', { success: true, user: params.user });


Firing an event as a response is preferable if you can get away with it so everyone can know what just happened, especially if it was successful, to give other parts of your application knowledge of what is going on.  Sometimes you do not need any response - like logging.


And sometimes you need a specific response directly back to you, for instance state information.


That's it for this round - stay tuned for MUCH more!

No comments:

Post a Comment