BizTalk Utilities CV ,   Jobs ,   Code library
 
Go to the front page to continue learning about XML or select below:

Contents

ReBlogger Contents

Previous posts in XML

 
 
Page 3971 of 19626

Dojo XHR Plugins; How do you want your XHR today?

Blogger : Ajaxian Blog
All posts : All posts by Ajaxian Blog
Category : XML
Blogged date : 2008 Apr 15

Neil Roberts goes into the XHR Plugins that Dojo uses and how you can extend the system to have your own.

If you look at dojo.xhrGet you will see "Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml", but:

What you may not know is that the handleAs parameter is merely a way of specifying what plugin to use. Knowing where these plugins are, how they work, and how they can be adapted to suit your project will allow you to make repetitive tasks easy and less error-prone.

He starts by piggybacking on the json style callback, and adds a hook so when you do a query, if there are updated objects out there, they come back in the JSON so you can deal with them without having an extra remote call:

JAVASCRIPT:
  1.  
  2. dojo._contentHandlers.json = (function(old){
  3.   return function(xhr){
  4.     var json = old(xhr);
  5.     if(json.updated){
  6.       processUpdatedObjects(json.updated);
  7.       delete json.updated;
  8.     }
  9.     return json;
  10.   }
  11. })(dojo._contentHandlers.json);
  12.  

Next, Neil goes on to write a system that auto updates nodes:

JAVASCRIPT:
  1.  
  2. dojo.xhrGet({
  3.   url: "node-updates.php",
  4.   handleAs: "node-update-server"
  5. });
  6.  
  7. dojo.xhrGet({
  8.   url: "node-content.php?node=sidebar",
  9.   node: "sidebar",
  10.   handleAs: "node-update"
  11. });
  12.  

which is as easy as:

JAVASCRIPT:
  1.  
  2. dojo.mixin(dojo._contentHandlers, {
  3.   "node-update-server": function(xhr){
  4.     var json = dojo._contentHandlers.json(xhr);
  5.     dojo.forEach(json.updates, function(update){
  6.       var node = dojo.byId(update.id);
  7.       if(node){
  8.         node.innerHTML = update.html;
  9.       }
  10.     });
  11.   },
  12.   "node-update": function(xhr){
  13.     var node = dojo.byId(xhr.args.node);
  14.     if(node){
  15.       node.innerHTML = dojo._contentHandlers.text(xhr);
  16.     }
  17.   }
  18. });
  19.  

In conclusion:

Dojo makes it incredibly easy to change the way that your Ajax calls work. You can change the format of JSON your server returns without having to change any of your callbacks, you can change the handleAs type for a single function to change the data given to your callback, you can get rid of callbacks altogether and use the arguments to your xhr call determine what should be done with your results.


Read comments or post a reply to : Dojo XHR Plugins; How do you want your XHR today?
Page 3971 of 19626

Newest posts
 

    Email TopXML