Wednesday, August 15th, 2007

Building an event-based Ajax application

Category: Dojo, JavaScript

Dojo has had a publish/subscribe system forever. With 0.9 it gets even better, and this writeup discusses how you can wire up your Ajax application using pub/sub.

If you have an application that uses devices like deferred loading, or “parse on demand”, wrapping it with an initializer helps keep it that way.

The final code example is:

javascript

  1. acme.topic = function(){
  2.     // current topic argument hash map
  3.     this.current = {};
  4. };
  5.  
  6. dojo.extend(acme.topic, {
  7.     subscribe: function(topic, scope, method, acceptNull){
  8.  
  9.         var hdl = dojo.subscribe(topic, scope, method)
  10.  
  11.         //Initializer - called only once, on subscribe
  12.         if(acceptNull || this.current[topic]){
  13.             // Converting arg to a non-array if it is not a length > 1
  14.             var a = this.current[topic];
  15.             var arg = (a == null) ?  null : (a.length == 1) ? a[0] : a;
  16.  
  17.             //NOTE! Only accepting string methods
  18.             scope[method].call(scope, arg);
  19.         }
  20.         return hdl;
  21.     },
  22.  
  23.     publish: function(topic, args){
  24.         dojo.publish(topic, args);
  25.         // Store published arg, in the event a subscribe is called later
  26.         this.current[topic] = args;
  27.     },
  28.  
  29.     unsubscribe: function(handle){
  30.         // Pass-through. Could be called directly.
  31.         dojo.unsubscribe(handle);
  32.     }
  33. })

Posted by Dion Almaer at 7:02 am
Comment here

++---
2.6 rating from 46 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.