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

which you can use when you create the store:

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

Posted by Dion Almaer at 8:50 am
Comment here

+++--
3.7 rating from 22 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.