Saturday, November 10, 2007

Dojo Grid + Jester + Rails = RESTful grid goodness

I've been experimenting with Javascript component frameworks lately, and that let me to look at Dojo. With their 1.0 release, they have added what looks to be a very powerful Grid component. I thought it would be fun to see how easy it is to get it talking with Rails. It proved to be not much code at all, and I think, kind of nifty. Here's how to do it.

Create a Rails app with a RESTful service

Not gonna go thru how to make a rails app, I'll assume you know that already. I created a little RESTful service with the scaffold generator something like this:

script/generate scaffold_resource Car make:string year:integer

Install Jester

When I found Jester it was one of those Open Source Moments for me. You know, the ones where you think: "Hey, wouldn't it be cool if you could..." and then Google and find out someone has already done it. Jester is basically ActiveResource in Javascript. The result makes so ridiculously easy to talk to RESTful services it's not even funny. I installed by unzipping the script and dropping jester.js in public/javascripts in my Rails app.

Install Dojo 1.0

Go get it, unzip it, drop it into public/javascripts. Nuff said

Write the code

And now for the fun part :) We'll start with a simple grid that pulls in data by making a RESTful call to our Rails app using Jester. Later on we'll enhance it to make it editable. First thing you need to know about Dojo is that it is CSS driven. This is definitely a good thing IMO, but it does mean you have to include the right CSS or it won't work at all, trust me ;) So make you sure you include the Dojo Grid CSS like so:

5 <style type="text/css">
6 @import "/javascripts/dojo-release-1.0.0/dijit/themes/tundra/tundra.css";
7 @import "/javascripts/dojo-release-1.0.0/dojox/grid/_grid/Grid.css";
8 @import "/javascripts/dojo-release-1.0.0/dojox/grid/_grid/tundraGrid.css";
10 </style>

Next, we'll need to include Jester and Dojo:

12 <%= javascript_include_tag :defaults %>
13 <%= javascript_include_tag "jester" %>
14 <script type="text/javascript"
15 src="/javascripts/dojo-release-1.0.0/dojo/dojo.js"
16 djConfig="parseOnLoad: true"></script>

Including Jester is just a matter of including using the standard javascript_include_tag helper, but dojo is a little wierd. You'll notice the djConfig attribute for starters. How does this even work? djConfig is not even a valid attribute for a script tag, right? As best I understand it, and someone please jump in if I'm wrong, dojo has a parser of it's own that comes along after your page load sand does things to it. This let's you add dojo components to your page "declaratively", or in html, instead of have to use so much javascript. Kind of interesting.

Now let's look at the script block that sets up the objects our grid will need:

18 <script type="text/javascript">
19 dojo.require("dojo.parser");
20 dojo.require("dojox.grid.Grid");
21 dojo.require("dojox.grid._data.model");
23 Resource.model("Car");
24 cars = Car.find("all");
26 var model = new[{key: "make"}, {key: "year"}], cars);
28 var structure = [ {
29 rows: [[
30 {name: 'Make'},
31 {name: 'Year'}
32 ]]
33 } ];
36 </script>
The first thing you'll notice is those dojo.require statements. These are how you tell dojo to go get all of the pieces it needs. Dojo is broken down into lots of individual javascript files, and while you could just include them all in script tags, that would be kind of a pain. dojo.require basically says "go get this piece and all of it's dependencies". It makes it easier to use some of dojo and not all of dojo as well.

Next we see Jester in action. Kind of puts dojo to shame from an ease of use standpoint, doesn't it? You tell Jester which model you want, and it makes a javascript class for you. We then call find all and it gives us back an array javascript proxy objects with the fields and methods you would expect. Like I said, ridiculously easy. There are options to have it do find (and save) asynchronously as well, which you would probably want to use for a real application.

Next we setup some objects our dojo grid needs. The first is a model, it tells dojo where to get it's data from. We're able to use of the built in types of models, This kind of model will display an array of Javascript objects, which, conveniently enough, is exactly what we got back from the call to find. We have to give it a little more information, though, namely what properties to display in which columns of our grid. This is what we're doing in the first argument to the constructor. The second argument is our array of cars we got back from the call to Car.find("all").

Finally, we have an object that tells how we want our grid organized. I have to say this seems a lot more complicated than I'd like. It seems to me sometimes dojo is more focused on making the hard things possible than making the simple things simple. So I'm not even going to try to cover all the details of the structure object here, but briefly dojo grid structures consist of an array of views which have an array of rows which have an array of subrows. Phew. I think it would be possible to come up with a simpler structure object for simpler cases, but that would require more dojo-fu than I have yet.

At last, we're ready to put in the html for our grid. Here it is:

42 <div id="grid" dojoType="dojox.Grid"

43 model="model" structure="structure"
44 autoWidth="true" autoHeight="true">

45 </div>

Not much to it is there. Notice how we can set properties of our grid with html attributes. This is what the dojo parser does for us, as I understand it. Here we're passing in the model and structure we created in our script block.

So this is all that's required to use the dojo grid component and have it pull data from a REST service implemented in Rails. In my next post I'll show you how to have it be editable and save it's data using thru REST as well. It's easier than you might think.


Leo said...

Wow, I have to say. Wow, how come nobody came across your post before. I have always been wondering what else can REST service do and you have just answered that.

Dojo Grid is super nice as well and Jester is just like the catalyst to it all. Thanks for a really good post.

nullobject said...

This is very cool, I'm trying to integrate Ext + Jester + Rails myself. Have you managed to resolve how to do paging in the grid using only Jester to do the RESTful requests? This is what I'm still scratching my head about...

Songa said...

Thanks for great post!

I am trying to implement your solution but i am getting a stack overflow error at line 403, I presume this is in the jester.js file but I am not sure why it is happening.

please advise whenever you have the time.


Songa said...

I figured it out, I was not addressing my model properly!

Anonymous said...

Day night,gold für wow the moon or on world of warcraft gold the tree,cheap wow gold Hao Jie pouring down the moonlight, as if accompanied by Xiaotu Feifei enter sweet dreams. In the dream, a dream Feifei about his sister to the moon night. Will open the door,wow gold kaufen go down the moon sister.mesos Xiaochanzouxia take is that they did not see the moon sister. At that time, anchored at the tree on the moon sister saw Xiaochan, they yelled loudly: "Feifei, Feifei, I tree, the tree, I." Xiaochan sit at the moon to his sister, who Daizhaoxiaochan came wow geld to the beautiful pond. Only, water,maple story mesos everywhere in the lush leaves and beautiful flowers.maple story items A frog squatting lotus leaf, see Xiaochan, surprised and said: "Xiaochan,wow gold farmen you can even sit on the moon. You simply It's amazing!maple story money I am sure that you are the first animals to the moon by the animal. good,wow leveling I envy you!Maple Story Accounts "Xiaotu listening, happy to smile. Then, with the moon sister Xiaotu to its home.powerlevel Only, the moon sister's home stars are everywhere. The eyes of a star a Zha Zha,world of warcraft power leveling like Xiaotu greeted the arrival of a mouth, like: "Xiaochan, Hello, we at the Moon Palace waiting for your arrival."maple story powerleveling Xiaotu listened

Anonymous said...

Weekends to peopleig2tmean that they can have a two-day wowgold4europe good rest. For example, people gameusdcan go out to enjoy themselves or get meinwowgoldtogether with relatives and friends to talk with each storeingameother or watch interesting video tapes with the speebiewhole family.
Everyone spends agamegoldweekends in his ownmmoflyway. Within two days,some people can relax themselves by listening to music, reading novels,or watchingogeworld films. Others perhaps are more active by playing basketball,wimming ormmorpgvipdancing. Different people have different gamesavorrelaxations.
I often spend weekends withoggsalemy family or my friends. Sometimes my parents take me on a visit to their old friends. Sometimesgamersell I go to the library to study or borrow some books tommovirtexgain much knowledge. I also go to see various exhibition to broadenrpg tradermy vision. An excursion to seashore or mountain resorts is my favorite way of spending weekends. Weekends are always enjoyable for me.
igxe swagvaultoforu wowgold-usaignmax wowgoldlivebrogame thsaleGoldRockU

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa

aiya said...

Office 2010is powerful!
Microsoft Office 2010is the best software in the world.
Microsoft wordis so great!
Office 2007makes life great!
Many people likeMicrosoft Office.
Microsoft Office 2007is welcomed by the whole world.
Office 2007 keyis available here.
Office 2007 downloadis on sale now!
Office 2007 Professionalbring me so much convenience.
Outlook 2010 make life wonderful!
Microsoft outlook is my love.
Microsoft outlook 2010 is convenient!
Windows 7 is convenient!

teramoney said...

buy eden gold
Runescape gold
buy Runescape gold

cheap wow gold
cheapest wow gold
lotro gold

Tera online
Tera gold

soolo said...

However, sumptuous texture and exquisite craftsmanship will not be covered by this simple dressing. It will be dazzling to accent your high-end taste.cambridge satchel|cambridge satchels|cambridge satchel|cambridge satchels|cambridge satchel companycambridge satchel co|the cambridge satchel company|cambridge satchel bag|cambridge satchel company briefcase bag|the cambridge satchel|cambridge satchel company review|cambridge satchel company 11 satchel|cambridge leather satchel|cambridge satchel company bag|satchel cambridge|cambridge satchel company discount|cambridge satchel bags|cambridge satchel company discount code

liuyunxin said...

I really enjoy your posts as I learn a lot from them. I also broaden my thinking as far as what I can use and do with thingsHere useful link:
diablo 3 gold
guild wars 2 gold
guild wars 2 gold
diablo 3 gold
diablo 3 gold
guild wars 2 gold
tera gold
diablo 3 gold
guild wars 2 gold
guild wars 2 gold
diablo 3 gold
diablo 3 gold
guild wars 2 gold
tera gold

christina said...

From the advertisements, we are able to research theirs propagate priority. The complete atmosphere is as following: the framing is situated within of tiffany stores the romantic island, using the intent of constructing an fast and at ease atmosphere. The type Anne Vyalisyna wears a apparel with flouncing and coach on sale different delicate fits walking for the trip. The visual appeal of gentle yellow, pale pink and gentle blue will make the complete assortment diffuse the inhale of youthful lady and pleasant mood; she appears like really graceful, easy-going and converse store livelier. LV bag 2011 is mainly developed using the gentle yellow, pale pink and gentle blue colors, the ads are filmed near to this theme color.

Miller Yu said...

The visual Diablo III itemsappeal of gentle yellow, pale pink and gentle blue will make the complete assortment diffuse the inhale of youthful lady Buy RS Goldand pleasant mood; she appears like really graceful

rscredits said...

buy runescape gold with 5% discount code:CHRISTMAS.


Free 200M runescape gold Giveaway on RSorder Flash Sale! Time: 03:00 AM on December 21, 2012 GMT

To know more:

Like RSorder Facebook to Get 200M Free rs gold! If our facebook fans reach to 10,000, we will send out totally 200M free RS gold.

Rsorder facebook :

Detailed info at:

Fast delivery can be assured if you buy rs gold pay by Western Union at Rsorder!

AntoL-Nyo said...

HD kaliteli porno izle ve boşal.
Bayan porno izleme sitesi.
Bedava ve ücretsiz porno izle size gelsin.
Liseli kızların ve Türbanlı ateşli hatunların sikiş filmlerini izle.
Siyah karanlık odada porno yapan evli çift.
harika Duvar Kağıtları bunlar
tamamen ithal duvar kağıdı olanlar var

AntoL-Nyo said...

Ben istanbuldan selda 22 yaşında konfeksiyon içşisiyim Amatör Porno sizleri bekletmeden hemen hikayeme geçiyorum.. Biz 5 katlı bir binanın en üst katında yaşıyorduk ve bir öğlen paydosunda sevgilim beni Anal Sikiş aradı evdeydim çünkü evle iş yerim arasında 2 dakika bile yoktu.. Bende Asyalı Porno sevgilime benden telefon beklemesini söyledikten sonra evin durumuna baktım evde kardeşlerim ve annemin Esmer Porno birkaçtane arkadaşı vardı bu iş imkansızdı tekrardan düşündüm ve çatı katı aklıma geldi sevgilime telefon açıp çatıya çıkmasını ve Fantazi Porno beni beklemesini söyledikten sonra telefonu bir süre elime almadım anneme işe gidiyorum dedikten sonra Gay Porno hemen üst kata çatıya çıkıp sevgilimin
dudaklarına yumuldum az bir süremiz Götten Sikiş vardı ve çok istiyordum onu hemen önünde diz çöküp sikini çıkardım kocaman olmuştu bile... Özlemişti beni HD Porno bitanem başladım sikini yalamaya kafasını öpüyor onu çıldırtıyordum sevgilim saçlarımdan tutmuş ağzımı keyifle sikerken çatı katının kapısı açıldı toparlanamadan Lezbiyen Porno komşunun şişman oğlu efecan gelmişti ben dizlerimin üzerinde sevgilimin Liseli Porno siki ağzımda yakalanmıştım hemen bu halimizi gören komşu oğlu Sarışın Sikiş kaçarcasına gitti.. Sevgilim bir süre güldükten Türbanlı Porno sonra bu şişko neden kaçtı korktu herhalde onu sikicem sandı galiba dedikten sonra bir kahkaha daha attı ben sevgilimin Türk Porno sikine deli gibi saldırıyor yalıyor emiyordum boşalmasını istiyor Zenci Porno sütünü içmek istiyordum sevgilim ağzımı sike sike boşaldı hepsini yuttum bir damlasını ziyan Porno etmedim ve sevgilimle vedalaşıp ayrıldık... Ben her defasında sikiş yapmadan önce yazporno diye olan türkçe siteden Porno izle bölümüne girip seyrediyorum azdıktan sonra şahane sikiş ile gözleri kamaştırıyorum.

Jessica Colin said...

Worry is the fear we manufacture; it is a choice. Conversely, true fear is involuntary; it will come and get our attention if necessary. But if a parent or a child feels fear constantly, there is no signal left for when it’s really needed. Thus, the parent who chooses to worry all the time or […]

pacetransportationinc | | | | | |

businessmerch |

practical-computersinc | | |

Amna Khan said...

I think the way you write feels like having so much passion and you have put it in a way that everyone can understand. Must appreciate the great posts you have written here |

dehollisterco | | | |

Amna Khan said...

Ik spreek niet over scheurtjes in oude banden, maar in tamelijk nieuwe banden. En dan bedoel ik 1-2 jaar. De cracks waar Sheldon over spreekt is iets heel anders. Die zijn het gevolg van contact met rommel op de weg. De scheurtjes waar ik het over heb, zitten in de flanken en het zijn er honderden. De oorzaak is slechte hechting van de rubbercompound aan de koordlagen, of krimp in de rubbercompound. Dat heet gebrekkige kwaliteit. |

experiencetheserenity | | |

jabuconsulting |

prathap kumar said...

JavaScript Training Course is essential to the achievements of an individual. Perhaps its most positive benefit is better employees. A company develop the potential of an employee, and part of the way a company encourages improvement is through training.

JavaScript Course
Online Javascript Course
Javascript Course Online
Free Online Javascript Course

AngularJS Interview Questions
JavaScript Tutorials