Activate your free membership today | Log-in

Friday, June 27th, 2008

Working with Web Services with ease; dojo.data and the WikipediaStore

Category: Dojo

<p>Revin Guillen has posted about the Dojo dojo.data API and how you can layer access to Web services in a very elegant way.

His example shows building access to Wikipedia (demo):

Dojo recently received a new data store that demonstrates exactly what we want: dojox.data.WikipediaStore. It does just what it sounds like, turning Wikipedia into a simple object you can query from your code. Building it with Dojo’s handy dojox.rpc package makes for a simple, compact, DRY implementation.

In only four steps:

  1. Create the web service object
  2. Declare the new data store, inheriting from ServiceStore
  3. Give it a fetch method
  4. Give it a _processResults method

The service descriptor looks like:

JAVASCRIPT:
  1.  
  2. {
  3.     "SMDVersion": "2.0",
  4.     "id": "http://en.wikipedia.org/w/api.php",
  5.     "description": "Wikipedia API",
  6.  
  7.     transport: "JSONP",
  8.     envelope: "URL",
  9.     additionalParameters: true,
  10.     target: "http://en.wikipedia.org/w/api.php",
  11.     parameters: [
  12.         { name: "format", optional: false, "default": "json" }
  13.     ],
  14.  
  15.     services: {
  16.         query: {
  17.             parameters: [
  18.                 { name: "action", type: "string", "default": "parse" }
  19.             ]
  20.         }
  21.     }
  22. }
  23.  

which you can use when you create the store:

JAVASCRIPT:
  1.  
  2. dojo.require("dojo.io.script"); // for cross domain JSONP
  3. dojo.require("dojox.rpc.Service");
  4.  
  5. dojo.addOnLoad(function(){
  6.     var mu = dojo.moduleUrl("dojox.rpc.SMDLibrary", "wikipedia.smd");
  7.     var wikipedia = new dojox.rpc.Service(mu);
  8.  
  9.     wikipedia.query({
  10.         action: "parse",
  11.         page: "Main Page"
  12.     }).addCallback(this, function(article){
  13.         dojo.body().innerHTML = article.parse.text["*"];
  14.     });
  15. });
  16.  

Related Content:

Posted by Dion Almaer at 8:50 am
Comment here

+++--
3.7 rating from 21 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.