- The Book of Dojo
- Quick Installation
- Hello World
- Debugging Tutorial
- Introduction
- Part 1: Life With Dojo
- Part 2: Dijit
- Part 3: JavaScript With Dojo and Dijit
- Part 4: Testing, Tuning and Debugging
- Part 5: DojoX
- The Dojo Book, 0.4
Advanced Topics
Submitted by ashish on Thu, 08/23/2007 - 07:14.
So far we have seen how to use markup to accomplish drag and drop. In this chapter we will have a look at some features, we have not discussed. This chapter features a sample 'Shopping Cart Application'. You can download the related files and refer to the 'readme.txt' to try it out. Everything we will discuss in this chapter has gone into the making of this application.
Typically, items that particpate in DnD would originate from server in one form or another. In that case they can't be hard-coded at design time, they have to be created dynamically at runtime. Also it makes sense to assume that the server will only give data (XML,JSON,CSV..). HTML elements (UI) for each of this data item will have to be created at client side using javascript. The node creator function is meant precisely to do this !
Let us first have a look at the call to 'insertNodes()' function. The first parameter is boolean, if set to 'true' will result in marking the inserted nodes as selected. The second parameter is very important. It actually expects an array of javascript objects. Any object can be passed, but most probably you will want to pass data coming from server here. Important thing to know here is that the 'creator' function will be called for each object in the array. Every object in the array is passed to 'creator' function as the 'data' parameter. The creator function creates a HTML node based on our data object. Also, the creator function decides the 'type' and 'id' of node .You can pass any object in the array provided your creator function is capable of handling it.
What data would come from the server and how we would like to interpret is for us to decide. We need to write our 'node_creator' function accordingly. In this case, let us assume that using dojo.xhrGet(AJAX) call, we received the string 'RED,BLUE' from the server. So I have passed two string objects "RED" and "BLUE" in the call to 'insertNodes()'.
Our node creator function is a simple one. It creates a new <div> tag with unique id for each node, based on the value of 'data'. It also assigns 'type' to the corresponding DnD item. The return statement is very important. The creator function returns a javascript object containing the node to be inserted, data related to the node and type assigned to the node. It is possible to assign multiple types to a single node.
The 'hint' parameter is used to customize creation of avatar. Dojo does create a default avatar for you (which is a carbon-copy of the node being dragged). But at times you will want your avatar to show different information or to show the same information in different a way.
Clearing Items from Source/Target
To clear all items you can use the following code:
Iterating through all nodes in Source/Target
To iterate through all nodes in a source or target you can use the following code:
Simple Shopping Cart Application
This is a simple application which contains a PHP script that acts like a service URL and HTML page, which is the main UI. The HTML page talks to service URL using AJAX for getting list of shop items and saving of cart items. You may want to spend some time looking at the source for this example, to see how web applications involving DnD could be designed.
With the 'Test.php' script following actions are supported:
If you open the 'shopping_cart.html' page, you will see three buttons 'Save', 'Logout' and 'Reset'. Try dragging and dropping some items from 'Today's Special' on 'Shopping Cart'. Click 'Save' and add some more items on Shopping Cart. Now click 'Logout'. On the logout page, click 'Login Again'. You should see only the saved items in your shopping cart. If you click 'Reset' your shopping cart will become empty.
To try out the shopping cart application you need to download all the files and follow instructions in 'readme.txt'. These files are attached at the end. This is a very simple and rudimentary example, but still illustrates key concepts in making use of DnD in real world scenarios. This concludes our adventures with the DnD API in Dojo.
Shopping Cart Example Files
Please Note:
Creating Source/Target with javascript
To do this we need to place two container tags on the page. The following javascript code will create a Source and Target object for us.
var node_creator = function(data, hint){ var types = []; var node = dojo.doc().createElement("div"); if(data == 'RED'){ types.push("red"); dojo.addClass(node, "redsquare");} if(data == 'BLUE'){ types.push("blue");dojo.addClass(node, "bluesquare"); } node.innerHTML = data; node.id = dojo.dnd.getUniqueId(); return {node: node, data: data, type: types};}; c1 = new dojo.dnd.Source("c1", {creator: node_creator,accept: ["item"],horizontal: false,copyOnly: false}); c1 = new dojo.dnd.Target("c2", { creator: targetnode_creator ,accept: ["item"]}); c2.insertNodes(false, ["RED","GREEN");The following points should be noted:
- 'c1' and 'c2' are ids of <div> tags used to create source and target.
- 'node_creator' function needs to be specified. This is called for creation of each node. We will discuss this part in detail in the very next topic.
- 'copyOnly' set to true indicates that always a copy operation is performed (instead of moving nodes). If set to false 'CTRL' key needs to be used for copying.
- 'horizontal' set to true indicates horizontal alignment, else use vertical alignment.
- Nodes can only be inserted using call 'insertNodes'. First parameter if set to true will result in selection of the inserted nodes. Second parameter is an array. We need to understand the working of 'insertNodes' and 'node_creator' in more detail.
Typically, items that particpate in DnD would originate from server in one form or another. In that case they can't be hard-coded at design time, they have to be created dynamically at runtime. Also it makes sense to assume that the server will only give data (XML,JSON,CSV..). HTML elements (UI) for each of this data item will have to be created at client side using javascript. The node creator function is meant precisely to do this !
{"id": "S001", "name": "PENCIL", "price": "3.20", "rating": "3", "description": "A really cool product.", "img_url": "images/RED.png"} |
![]() |
![]() |
Sample JSON from server | HTML node created by the 'node_creator' function. | Customized avatar created using 'node_creator' |
What data would come from the server and how we would like to interpret is for us to decide. We need to write our 'node_creator' function accordingly. In this case, let us assume that using dojo.xhrGet(AJAX) call, we received the string 'RED,BLUE' from the server. So I have passed two string objects "RED" and "BLUE" in the call to 'insertNodes()'.
Our node creator function is a simple one. It creates a new <div> tag with unique id for each node, based on the value of 'data'. It also assigns 'type' to the corresponding DnD item. The return statement is very important. The creator function returns a javascript object containing the node to be inserted, data related to the node and type assigned to the node. It is possible to assign multiple types to a single node.
The 'hint' parameter is used to customize creation of avatar. Dojo does create a default avatar for you (which is a carbon-copy of the node being dragged). But at times you will want your avatar to show different information or to show the same information in different a way.
Clearing Items from Source/Target
To clear all items you can use the following code:
c2.selectAll(); c2.deleteSelectedNodes(); c2.clearItems();
Iterating through all nodes in Source/Target
To iterate through all nodes in a source or target you can use the following code:
var x = c2.getAllNodes(); for(i =0;i<x.length;i++) {//jsNode is javascript object for node //x[i] represents HTML element for the node var jsnode = c2.getItem(x[i].id);}
Simple Shopping Cart Application
This is a simple application which contains a PHP script that acts like a service URL and HTML page, which is the main UI. The HTML page talks to service URL using AJAX for getting list of shop items and saving of cart items. You may want to spend some time looking at the source for this example, to see how web applications involving DnD could be designed.
With the 'Test.php' script following actions are supported:
Method | URL | Result |
GET | Test.php?action=get_all_items | Returns JSON for all items in the shop. This is stored in a plain text file (data.txt). In real world scenario it would come from database. |
POST | Test.php?action=save_cart_items | Sends JSON for all items in the shopping cart back to server, where they are stored in Session. |
GET | Test.php?action=get_cart_items | Returns JSON for all shopping cart items, saved by user (with the intent of buying later) .These were saved in the Session. |
GET | Test.php?action=reset | All saved items in shopping cart are deleted. Session is cleared. |
If you open the 'shopping_cart.html' page, you will see three buttons 'Save', 'Logout' and 'Reset'. Try dragging and dropping some items from 'Today's Special' on 'Shopping Cart'. Click 'Save' and add some more items on Shopping Cart. Now click 'Logout'. On the logout page, click 'Login Again'. You should see only the saved items in your shopping cart. If you click 'Reset' your shopping cart will become empty.
Important: Since this is just a sample, in the file 'shopping_cart.html' , I have set
djConfig="usePlainJson: true"In real life scenario, this could make your page vulnerable to 'JavaScript Hijacking', I haven't bothered about this. It is recommended you use 'text/json-comment-filtered' as mime type while making XHR calls. This document contains good information on the security risks and ways to prevent it.
To try out the shopping cart application you need to download all the files and follow instructions in 'readme.txt'. These files are attached at the end. This is a very simple and rudimentary example, but still illustrates key concepts in making use of DnD in real world scenarios. This concludes our adventures with the DnD API in Dojo.
Shopping Cart Example Files
Please Note:
I am still working on this example. This is my first attempt with PHP programing :-). Any suggestion/optimizations are welcomed. This message will be removed once the work is reviewed officially.
Attachment | Size |
---|---|
item.jpg | 5.47 KB |
avatar.jpg | 3.46 KB |
data.txt | 989 bytes |
readme.txt | 662 bytes |
shopping_cart.html | 7.21 KB |
Test.php_.txt | 914 bytes |
logout.html | 249 bytes |
- Printer-friendly version
- Login or register to post comments
- Unsubscribe post
Example is not working
Hi Asish
I am new bie to the Dojo
I have downloaded the DOJO 0.9 and i am implementing DND
please can u tell the stepwise procedure for shopping cart example
Thnaks In Advance
The shopping cart example is
The shopping cart example is still 'work under progress'. Its almost complete. But if you are new to dojo, I suggest first you try out other examples first. Once you are through you can try the shopping cart example. It requires you to place all the files on webserver directory with PHP installed on it. You also need to setup Dojo toolkit files on the server.
im trying to create a simple
im trying to create a simple custom widget programatically, inside a dnd container... but it doesnt work
here is my thread in forum describing the problem
the WidgetCreator function is called inside another widget (only once on init), but it doesnt create the widget... its created only if i drag and drop other items in the same container... and whenever i drag and drop, the widget is created again
<style> images need updates
In 'shopping_cart.html', the 'background-image' references to 'set2_stop.png' and 'set2_copy.png' in the 'complete source' should be updated to reference the 'dndNoMove.png' and 'dndMove.png' images, respectively. These images are available in the 0.9 'dojo/resources/images' directory.
Also, since the cart allows 'copy' via the control key, possibly it would be interesting to see how to vary the images based on 'move' or 'copy' state of the current dragging operation.
JSON Security Issue
You will receive the following message in the Firebug console when running this example, 'please consider using a mimetype of text/json-comment-filtered to avoid potential security issues with JSON endpoints (use djConfig.usePlainJson=true to turn off this message)'.
Perhaps 'usePlainJson: true' should be added to the 'djConfig' attribute and a short explanation of its consequences would be appropriate here since this is a 'real world' scenario.
'Login again' Logout.html link invalid
The 'Login again' link in 'logout.html' should probably point to back to 'shopping_cart.html'.
serverside scripts
I'm assuming you're using php to demonstrate the state persistence, however not everyone is a php developer and I'd hate to have to setup a php environment just to see this working...
Why not use the offline module, stub it out on the client or host it where we can see a running example.
I am myself an ASP.NET
I am myself an ASP.NET developer! In fact this is one of the first PHP scripts that I have ever written in my life. I hated setting up PHP as much as you do. The only reason I choose PHP is, I thought it was easier to understand AND more popular than JSP, Rails etc.. If you check out the code, you will realize , it is simplest code one may come across in any language (hopefully !).
Right now, you can just try to translate it to your favourite language. Your suggestion of using offline module looks good...i'll check that out soon. But I am not in favour of introducing it in this part of book (assuming it would be somewhat complex). Since the section deals exclusively with DnD, a person with little Dojo knowledge should be able to make most out of it. Anyways, I will definitely consider your suggestion.
note on PHP using IIS
I set up PHP real quick on my box to run this, found permisson issues with the session save.
needed to network share the session directory php.ini
session.save_path="C:\DOCUME~1\MICHAE~1\LOCALS~1\Temp\php\session"
this is a very sloopy answer and IIS types can tell me a better one ?
moving
I guess it should be included some info on how to move nodes with javascript.
peer review
It's apparent to me after reading this when I really need to do something that this hasn't been peer reviewed for clarity or substance. So, if you don't mind, I will now. I'm hoping this is regarded as constructive criticism.
I'll stop here for now, but this page needs serious work. As the only page that talks about programmatically achieving DnD with dojo, it's lacking clarity. And as I mentioned in my comment above, I don't see the reason for having examples based on PHP, which this can easily be demonstrated in dojo alone, using dojo.data, dojo.xhr and other constructs which form the framework.