Activate your free membership today | Log-in

Friday, June 19th, 2009

Serial Asynchronous XmlHttpRequests

Category: Dojo, JavaScript

By default we should always favour asynchronous XHR to help the responsiveness of our Web applications. However, have you ever wanted a way to serialize your XHR calls because you needed to do things in sequence as B relied on what came back from A?

You could call a synchronous Ajax call, but that locks up the browser. Thibaud Lopez Schneider has written up his thoughts here showing the difference between synchronous Ajax:

and async calls with magic to serialize them:

He then went and created a simple example code generator at asynchronous.me. It is interesting to look at the code of the serialized version, and see that it doesn't do anything complex.... just passes in the next function to run as a callback:

JAVASCRIPT:
  1.  
  2. function run() { 
  3.     request1(function () { 
  4.         request2(function () { 
  5.             request3(function () { 
  6.                 done()
  7.             })
  8.         })
  9.     })
  10. } 
  11. function request1(callback1) { 
  12.     // request 1 
  13.     print("request1")
  14.     var xmlHttpRequest1 = new XMLHttpRequest()
  15.     xmlHttpRequest1.open("GET", "something1?hello1", true)
  16.     xmlHttpRequest1.onreadystatechange = function () { 
  17.         if (this.readyState == 4 && this.status == 200) { 
  18.             // response 1 
  19.             print("response1=" + this.responseText)
  20.             // continue execution in the callback 
  21.             if (callback1) { 
  22.                 callback1()
  23.             } 
  24.         } 
  25.     }
  26.     xmlHttpRequest1.send()
  27. } 
  28. function request2(callback2) { 
  29.     // request 2 
  30.     print("request2")
  31.     var xmlHttpRequest2 = new XMLHttpRequest()
  32.     xmlHttpRequest2.open("GET", "something2?hello2", true)
  33.     xmlHttpRequest2.onreadystatechange = function () { 
  34.         if (this.readyState == 4 && this.status == 200) { 
  35.             // response 2 
  36.             print("response2=" + this.responseText)
  37.             // continue execution in the callback 
  38.             if (callback2) { 
  39.                 callback2()
  40.             } 
  41.         } 
  42.     }
  43.     xmlHttpRequest2.send()
  44. } 
  45. function request3(callback3) { 
  46.     // request 3 
  47.     print("request3")
  48.     var xmlHttpRequest3 = new XMLHttpRequest()
  49.     xmlHttpRequest3.open("GET", "something3?hello3", true)
  50.     xmlHttpRequest3.onreadystatechange = function () { 
  51.         if (this.readyState == 4 && this.status == 200) { 
  52.             // response 3 
  53.             print("response3=" + this.responseText)
  54.             // continue execution in the callback 
  55.             if (callback3) { 
  56.                 callback3()
  57.             } 
  58.         } 
  59.     }
  60.     xmlHttpRequest3.send()
  61. } 
  62. function done() { 
  63.     // end 
  64.     print("done")
  65. }
  66.  

You can compare that approach to Dojo Deferred:

JAVASCRIPT:
  1.  
  2.     function run() { 
  3.         request1().addCallback(request2).addCallback(request3).addCallback(done)
  4.     } 
  5.     function request1() { 
  6.         // request 1 
  7.         print("request1")
  8.         var deferred = dojo.xhrGet({ 
  9.             url: "something1?hello1"
  10.             load: function (response) { 
  11.                 // response 1 
  12.                 print("response1=" + response);           
  13.             } 
  14.         })
  15.         return deferred; 
  16.     } 
  17.     function request2() { 
  18.         // request 2 
  19.         print("request2")
  20.         var deferred = dojo.xhrGet({ 
  21.             url: "something2?hello2"
  22.             load: function (response) { 
  23.                 // response 2 
  24.                 print("response2=" + response)
  25.             } 
  26.         })
  27.         return deferred; 
  28.     } 
  29.     function request3() { 
  30.         // request 3 
  31.         print("request3")
  32.         var deferred = dojo.xhrGet({ 
  33.             url: "something3?hello3"
  34.             load: function (response) { 
  35.                 // response 3 
  36.                 print("response3=" + response)
  37.             } 
  38.         })
  39.         return deferred; 
  40.     } 
  41.     function done() { 
  42.         // end 
  43.         print("done")
  44.     } 
  45.  

Posted by Dion Almaer at 6:45 am
12 Comments

++---
2.6 rating from 30 votes

Wednesday, April 15th, 2009

Speeding Up Urchin with Dojo, Part 2

Category: Dojo, Google

Last year, we covered Pete Higgin's blog talking about how to load Google Analytics in a more responsive manner. Google may not have improved the situation since then (really?), but the Dojo folks have packaged up Pete's script into the recently released Dojo 1.3 and Alex Russell recently posted a great summary of issues with Google Analytics and an example of the new code:

[Google Analytics] but it tends to load slowly. There are several reasons for this:

  • Another DNS lookup to resolve http://www.google-analytics.com/. This DNS entry is likely to be “warm” given how frequently ga.js is used on the web, but as Jim Roskind explained on the Chromium blog, it’s the outliers that kill you.
  • It’s kinda big. At 9K on the wire (22K unzipped), ga.js is kinda chunky for what it does most of the time, namely tracking a single page load.
  • The default instructions are bone-headed. They direct you to do a document.write() which is a blocking, synchronous operation WRT page loading. This is tres dumb. Reasonable people should just include ga.js with a <script> tag, but nearly nobody does. Turns out that sane defaults still matter.
  • Load times seem totally random. As with DNS lookup, ga.js’s latency varies wildly. This isn’t backed up by anything empirical, but many pages feel blocked by ga.js for a near eternity.

The code is now simplified into this:

HTML:
  1. <script type="text/javascript"
  2.   src="http://ajax.googleapis.com/ajax/libs/dojo/1.3/dojo/dojo.xd.js">
  3. </script>
  4. <script type="text/javascript">
  5.   dojo.addOnLoad(function(){
  6.     setTimeout(function(){
  7.       dojo.require("dojox.analytics.Urchin")
  8.       dojo.addOnLoad(function(){
  9.         var tracker = new dojox.analytics.Urchin({
  10.           acct: "UA-XXXXXX-X" // your tracking # here
  11.         })
  12.       })
  13.     }, 100)
  14.   })
  15. </script>

Check out Alex's blog entry for more details.

Posted by Ben Galbraith at 8:30 am
13 Comments

++++-
4.1 rating from 28 votes

Thursday, April 2nd, 2009

Stocker showcases Dojo

Category: Dojo, Showcase

SitePen has created Stocker "which demonstrates some of the more advanced capabilities of Dojo, including the newly released DataChart, the DataGrid, Data Store, Comet, Persevere, and BorderContainer. SitePen is also offering a one-day workshop where you will learn how to create Stocker yourself, but I’m here to give you a sneak peak of what Stocker is and how it works.

Stocker uses these technologies to emulate a stock monitoring application. We’re using made up data, but that’s actually more interesting. The Persevere server generates new stock items at certain intervals, and then pushes them to the browser with Comet. Then the Data Store updates its items and triggers an onSet notification. The DataGrid and DataChart are both connected to the same store, and are listening to that event. They then update their displays and show the stock items and their latest data."

Want to see what it would be like to develop using Persevere, DataGrid, DataChart, and friends!

Posted by Dion Almaer at 6:44 am
6 Comments

+++--
3.8 rating from 61 votes

Tuesday, March 31st, 2009

Dojo 1.3 Released along with Plugd

Category: Dojo

We have been using Dojo 1.3 release candidates for awhile on Bespin, and today the Dojo team released Dojo 1.3 just in time for Internet Explorer 8.1 (really? some people believed that? I know that it isn't quite April Fools......).

There are some nice usable APIs added to base such as:

JAVASCRIPT:
  1.  
  2. // create a div.
  3. var n = dojo.create("div");
  4.  
  5. // create a div with content and styles
  6. var n = dojo.create("div", { innerHTML:"hi!", style:{ height:"200px" } });
  7. // destroy the node safely
  8. dojo.destroy(n);
  9.  
  10. // place an anchor somewhere, before the node with id="someNodeId"
  11. var a = dojo.create("a", { href:"http://dojotoolkit.org" }, "someNodeId", "before");
  12.  
  13. // empty the contents of a node safely:
  14. dojo.empty("someNodeId");
  15. dojo.query(".nodes").empty();
  16.  
  17. // place a new LI in an UL at the first position
  18. dojo.place("<li>Newly created DOM Node</li>", "someUl", "first");
  19.  
  20. // complex creation in dojo.query. passes through dojo.place
  21. dojo.query("#myNode").addContent("hi there!", "first");
  22.  

You can also choose between Acme and Sizzle as the engine that powers dojo.query.

Pete also announced Plugd a very cool plugin that "is available as a standalone "dojo.js" replacement (just throw it in your project on top of dojo.js!) or as a 2k adapter to load a bunch of solid additional base API's. We'll be continually working to merge the best parts of plugd back into Dojo land, but for the time being they are provided as a separate entity, and are fully documented."

With plugd you can write code like this:

JAVASCRIPT:
  1.  
  2. $("p.baz")
  3.     .appendTo("body")
  4.     .addClass("bar")
  5.     .onclick(function(e){
  6.        e.target.innerHTML = "Wow, JavaScript";
  7.     });
  8.  

Doesn't look like Dojo does it? :)

I blathered on about this and some other items when I discusses how Alex and Pete kindly indulged me in a scoping exercise that "should never be used in production!" ;)

Posted by Dion Almaer at 11:44 am
7 Comments

++++-
4.4 rating from 43 votes

Monday, March 23rd, 2009

dojo.gfx in detail

Category: Articles, Dojo

Matthew Russell wrote the most in depth article on dojo.gfx that I have seen. It appeared in Linux Journal and has now been re-printed online.

The article runs the gamut. It starts off discussing the place that dojo.gfx lives in the Dojo world:

Then we learn about how gfx abstracts on top of the various underlying graphics subsystems that various browsers expose (Canvas, SVG, VML, Flash, Silverlight, ...). gfx will choose for you automatically, or you can ask to use a particular rendered:

HTML:
  1.  
  2. <script type="text/javascript"
  3.     djConfig="gfxRenderer:'canvas'"
  4.     src="http://o.aolcdn.com/dojo/1.2/dojo/dojo.xd.js">
  5. </script>
  6.  

Then we delve into the drawing API itself:

JAVASCRIPT:
  1.  
  2. dojo.addOnLoad(function() {
  3.     var node = dojo.byId("surface");
  4.     var surface = dojox.gfx.createSurface(node, 600, 600);
  5.  
  6.     rect1 = surface.createRect({
  7.         /* x and y default to (0,0) */
  8.         width : 200,
  9.         height:200
  10.     })
  11.     .setFill("red")
  12.     .setTransform([
  13.         dojox.gfx.matrix.translate(200,200),
  14.         dojox.gfx.matrix.rotategAt(45,100,100)
  15.     ])
  16.     ;
  17. });
  18.  

From here Matthew covers topics such as manipulating groups, and how you can make areas moveable, and the 2D charting API.

Posted by Dion Almaer at 6:42 am
1 Comment

++++-
4.1 rating from 25 votes

Thursday, March 19th, 2009

Observe Dojo Events

Category: Bookmarklets, Dojo, Utility

Speaking of bookmarklets, in a recent blog post Nathan Kurtyka discusses a scenario familiar to many Ajax developers:

However, I can’t even begin to think about how much time I’ve wasted hunting through source code hoping there might be some event I can subscribe to (e.g. “What event is published when someone clicks on a Tree widget node?”).

So naturally, he created a little something to scratch that itch:

I created a Dojo bookmarklet that can be used to log all events to the console.

So to not only see how rich Dojo is with event publishing (you probably haven’t been leveraging either), but to also see the bookmarklet in action, head on over Dojo Campus. Just enable Firebug, give the bookmarklet a click, browse the demos.. and behold — events everywhere!!

Check out the blog for the bookmarklet.

Posted by Ben Galbraith at 8:00 am
3 Comments

++++-
4.5 rating from 28 votes

Friday, March 13th, 2009

JavaScript API Viewer: Client-side parsing with Dojo

Category: Dojo, Utility

The uxebu folks have put together a really nice JavaScript API viewer that is entirely written in JavaScript a la Code Illuminated.

The docs are very impressive, and it is indeed cool to do this all on the client, so it works offline just as easily as online. The team talked about the various documentation formats and how they came to the conclusion on what they were going to use. Nice stuff!

Posted by Dion Almaer at 5:52 am
5 Comments

++++-
4.3 rating from 26 votes

Tuesday, March 10th, 2009

Time Killer: Create o’ Dev

Category: Dojo

Here's some fun from the Dojo team. Last year during The Ajax Experience, I remember Peter Higgins taking a snapshot of me. I really didn't think much of it as we were all taking pics of the conference and it was cool to meet the Dojo team. Little did I know that it would turn into something more nefarious!

Enter, the "Create o' Dev"! Peter, along with some other hoodlums, created a Dojo-powered app that allows you to create a mashup of faces into what can only be described as a JS "horror of horrors"!

One demo you have likely not seen: Create o' Dev - showcasing Nicola Rizzo's dojox.fx.flip code and Chris Barber's LightboxNano ... This code has been sitting idle for some time now -- starting as a prototype a The Ajax Experience 2008 (Boston) where I had to pleasure of boarding with Nikolai Onken, Tobias Klipstein, and Wolfram McCain (all of Uxebu, and who, when combined, create one incredibly ugly developer) ...

Dyllan Schiemann said it perfectly:

It's a great example of using Dojo effects in a lightweight manner to create your own Ajax developer... I had no idea my face could look so scary when replaced with John Resig's lips and Rey Bango's nose

Oh the horror!

Posted by Rey Bango at 12:18 pm
Comment here

+++--
3.5 rating from 32 votes

Monday, March 9th, 2009

Dojo 1.3 is coming

Category: Dojo, JavaScript

Alex Russell has posted on Dojo 1.3b3 which we have actually been using on Bespin.

So why should you be switching to Dojo or upgrading to 1.3? You can dig through the nearly 500 fixed bugs or the tentative release notes yourself, but broadly speaking, we’ve hit all of our major stated targets for 1.3: IE 8 compatibility, major performance improvements throughout the whole system, and enhancements that make the APIs you already know that much more powerful and useful. I don’t want to get into specifics since Pete’s release announcement will include much more detail, but I’ll outline some of the changes to just the CSS query engine since that’s the system I worked on most for this release (continued after the jump).

Alex goes on to talk about the nitty gritty on some of these features. For example, he talks about the guts of "Acme", the latest CSS engine (that you can use stand alone and how it has changed due to the reality of querySelectorAll and the enhanced AST generator.

Posted by Dion Almaer at 6:39 am
2 Comments

++++-
4 rating from 30 votes

Thursday, March 5th, 2009

Dojo + Rails = Drails?

Category: Dojo, Rails

Bob Remeika pointed us to his recent labor of love: Drails:

Introducing Dojo support for Ruby on Rails!

drails is a helper library for using Dojo alongside Rails. It provides a Dojo implementation for all of the Rails helpers that would normally generate Prototype/Scriptaculous code so now ajaxifying your Rails application with Dojo is as simple as using the built in support that Rails already provides for Ajax, effects, and drag-and-drop.

Along with this release, drails also includes support for the following:

- Generating Dojo Dijits (along with the appropriate test files)

- Generating modules (along with the appropriate test files)

- Generating a dojo build profile based on the scripts that currently reside in your application

- Rake tasks for creating a dojo build which can easily be added to a capistrano task for deployment

I wanted to say a big thank you to all that have helped, especially Jon Moeller and the Dojo Foundation, for providing great ideas and code during GSoC. The project has been a long time coming and I'm very happy to say that it's finally at a point where it can be used.

The source and installation instructions are available on github:

http://github.com/foobarfighter/drails/tree/v1.0.0

Anyone using it yet?

Posted by Ben Galbraith at 6:00 am
11 Comments

+++--
3.7 rating from 23 votes

Thursday, February 26th, 2009

Ajaxian Featured Tutorial: Styling Dijit Form Elements

Category: Dojo

The Dijit UI library brings a ton of visual capabilities to the table and I think most people look to it for the power and simplicity of rendering well made user interface components such as grids, modals and calendars. Another aspect that people may overlook is it's excellent form handling capabilities and in this tutorial, Mike Wilcox walks you through the steps of enhancing the appearance of Dijit form elements:

In this post, I’ll show you how to set up your form with the proper style sheets, and do some minimalist CSS targeting to adjust each form so they’ll all be the proper size. The result will be a style sheet base that you can use and modify to create custom Dijit forms.

The tutorial is squarely aimed at users of the popular Dojo framework and it's companion UI library, Dijit and will show the flexibility and power of the theming capabilities of the frameworks. The tutorial focuses on creating a form that is styled to look like this using the built-in theming capabilities of Dijit:

While their are many methods of doing this via CSS or other styling frameworks, the advantage for Dojo users is that the capabilities are baked straight into the framework and helps to eliminate some of the overhead of including other frameworks or services as well as learning another framework.

Posted by Rey Bango at 10:25 am
1 Comment

++++-
4.3 rating from 25 votes

Wednesday, February 18th, 2009

Queued: a Netflix Queue Manager Using Dojo and AIR

Category: Dojo, Showcase

SitePen, via Adobe sponsorship, has created an open source queue manager for Netflix called Queued.

The entire Dojo toolkit contains much more functionality than any single application needs, so the task of building applications often comes down to figuring out what style of coding you’ll use rather than learning how to use different components and figuring out how to glue them together. For Queued, we ended up with:

  • a single HTML file for the main window
  • dAIR for Dojo/AIR integration (window handling, etc)
  • dijit for layout (BorderContainer and friends)—but only for layout; we wanted to show that you can build compelling experiences without having to include (or learn!) the entire toolkit
  • unobtrusive behavior implementation using dojo.behavior, which made it very easy for our design & CSS guys to be productive without conflicting with the JS guys (and vice versa)
  • dojox.dtl for most widget templating
  • drag and drop for queue re-ordering
  • various animations for polish
  • Dojo’s build system (we distill everything into a single dojo.js and qd.js for the production app)

Since Queued is as much a demonstration of Dojo as it is of AIR, we took special care to keep the code hackery to a minimum—in addition to simply working correctly, we needed the code to be 1) easy to follow and 2) instructive for developers interested in learning how a good Dojo app can be put together. Everything’s nice and organized.

Posted by Dion Almaer at 12:31 am
Comment here

++++-
4.1 rating from 28 votes

Tuesday, February 10th, 2009

Drag and drop your widgets in a portal with Shindig and Dojo

Category: Dojo, Showcase

Matthew Russell has taken Shindig, an OpenSocial implementation, and added the shine that you need in a portal including drag and drop of the components.

Click the image above to see it in action. Matthew posts some of the details of the implementation:

  • When doing anything like this, you need infrastructure. For this part of the project, Dojo streamlined tons of things like setting up event handlers, styling nodes, getting coordinates on the screen, abstracting a lightweight fabric for drag-and-drop operations, and so forth. Currently, the code uses AOL’s CDN to keep things nice and simple, but you’d definitely want to use the build tools to consolidate and minify the code when it’s game time.
  • When an IFRAME is inserted into the DOM, it (re)loads. So, when you’re dragging an IFRAME all over the screen, its location in the DOM doesn’t change and it doesn’t continually reload because it’s just being positioned absolutely. It’s when the drag event ends that you’re faced with the reload event because you want to move it into its new column (versus trying to maintain the geometry of never manipulating the DOM tree and keeping track of everything in a snap-to-grid fashion.) Anyhow, that’s the approach we took. The one reload event that takes place when the gadget being drug reaches its final destination seemed more reasonable than all of that geometry. Other than the frame getting drug around, no other IFRAMES ever get removed and reinserted, so they never have to reload.
  • For security reasons, Shindig renders gadgets inside of their own individual IFRAMEs versus rendering gadgets in an element like a DIV. That may not sound like a big deal, but it does bring up a few more implementation details worth noting. The first one that comes to mind is that when you’re dragging a DIV that contains an IFRAME, it’s not uncommon for the mouse to occasionally slide ever so slightly into the IFRAME. Unfortunately, the IFRAME then captures mouse events, and then drag-and-drop starts to get choppy and wig out a bit. You can work around this by creating a transparent overlay and placing it on top of the IFRAME during drag events so that the IFRAME can never capture those mouse events. Overlays also come in handy when you popup menus on the titlebar and want them to disappear when the user clicks anywhere else on the screen (including in other IFRAMEs.) One day, hopefully, Caja will kill those IFRAMEs, which will also probably help performance a bit (especially on IE.)
  • There are a few peculiarities that arise when you remove the last element from a container like a DIV, so one way you can deal with this is to ensure it always has a minimum height and width by placing an element in there that spans the width of the column and has a minimal height so that it can accept drag events.
  • As always, there are always a few special cases, so you have to do a little extra bookkeeping here and there. Hopefully the code is commented well enough that it’s not hard to follow. All in all, it’s only about 150 lines for the drag and drop mechanics, including whitespace.

All of this work has been done for Life360.

Posted by Dion Almaer at 6:21 am
4 Comments

+++--
3.9 rating from 19 votes

Tuesday, February 3rd, 2009

Doculicious: On-line Form Designer with PDF Output

Category: Dojo, Showcase

Chris Carpenter at Digital Carpenter sent us a link to one of his projects: Doculicious. It's a fairly complete form builder product, including a GUI form designer (complete with undo, floating collapsable attribute palette, etc.), cool on-line form entry interface (also with undo), and PDF export.

Doculicious uses Dojo under the covers. Nice work!

Posted by Ben Galbraith at 8:00 am
Comment here

++++-
4.5 rating from 21 votes

Friday, January 30th, 2009

Becoming More Productive With JavaScript and Vim Screencast

Category: Dojo, Tutorial

Matthew Russell has created a nice screencast showing how to be more productive in Vim:

I’ve been doing some reflecting this week on how I can work smarter (instead of harder), and one of the things I came up with was adding a few more tools to my Vim repertoire. I spend more than half of my engineering time in Vim (the other half usually being in a web browser), so I figured that a few minutes here and there would eventually add up in a big way.

In hopes of inspiring you to do the same, I put together a short screencast (~4mins; 14.5MB QuickTime file) that talks you through how to generate a custom tags file for Dojo’s API and the keystrokes to put it to work. Although I’m specifically using Dojo, I think this technique should probably apply to a lot of other toolkits as well assuming that they define API call in a consistent manner that can be approximated by a regex.

But like anything else with Vim, there are always multiple ways of accomplishing the very same thing, so I make no guarantees that there aren’t simpler ways of getting this done — but I can say that this way gets the job done, and is pretty easy to get working on your own system.

By the way, here are links to the generateTags.sh script and the tags file (for Core) mentioned in the screencast. I’ve slightly tweaked the tags file to remove duplicate tag names and a few things that weren’t really parts of the public API (regexes are obviously imperfect heuristics). I can’t say that the tags file may not be missing a few API calls, but tags are easy enough to add in manually if you do notice any omissions.

How do you extend your tools to give you a hammer that is suited to your work?

Posted by Dion Almaer at 6:29 am
3 Comments

+++--
3.3 rating from 17 votes

Tuesday, January 20th, 2009

Dojo Zoomer - Sweet Image Cropping Widget

Category: Dojo

I love projects that evolve from minor functionality to full-blown apps, especially with the help of a strong community like Dojo users. This is precisely what happened to Peter Higgins:

Dojo Zoomer

began as a simple Drag and Drop / Constrained Mover example, and with the help of a couple #dojo community members took shape into a fully featured demo showing the power of the Dojo Toolkit.

By hovering over the image on the left panel, a cropper panel appears which dynamically displays the cropped portion of the image on the right-hand panel, allowing you to focus explicitly on the portion of the main image that interests you. Certainly an appealing capability for many sites including online retailers and photo management hubs such as SmugMug or Flickr.

The component extends from Dojo's Dijit library making it extremely customizable.

Honestly though, the best part of this widget is how so many members of the Dojo community jumped in to enhance the initial demo to its current state and produce a widget which is immediately usable for many purposes.

Thanks be to mi hermana, Allison Wildman, for contributing all the beautiful imagery, Ben and Nic for coming through on the advanced math and coordinate calculation, and thanks to Dojo for providing such out of the box components as a dnd.parentConstrainedMoveable and dojox.widget.ResizeHandle, making this exercise simply one of wiring the parts together and supplying images.

Posted by Rey Bango at 10:52 am
7 Comments

++++-
4.3 rating from 33 votes

Next Page »