Happy Life with Intuitive API in Smart Controls

By | June 15, 2010

In this post I will show you an example of how smartly built controls and API’s can make the developers programming life extremely enjoyable, hopefully this example will urge you in giving such a smart effort when you build your own control or API.

Lately I have been playing around with a very nice tree control based on jQuery called jsTree. One of the nice features is that it allows populating the tree through asynchronous calls with JSON data representation. In order to achieve that, you needed to provide the data by JSON special format suitable to the tree. This format, regrettably, is open to the JSON vulnerability Phil Haack talked about in his two posts here and here.
So to avoid this vulnerability I had to change this default data format of the tree, at least until the very end of the data flow just before the tree populates the data, only then I can change it back to the default format, like the following:

The format I need to send from server to avoid the vulnerability, but the tree wouldn’t understand:

 { "d" : [ { attributes : { id : "2", balance : "0.00000" },  data : "Child",  state : "closed" }  , { attributes : { id : "3", balance : "0.00000" },  data : "AnotherChild",  state : "closed" }  ] }

The format the tree accepts, to which I should change back before populating:

[ { attributes : { id : "2", balance : "0.00000" },  data : "Child",  state : "closed" }  , { attributes : { id : "3", balance : "0.00000" },  data : "AnotherChild",  state : "closed" }  ]

That would not have been possible if the tree control wasn’t smart enough to provide the developer with the “ondata” event (line 45) that happens exactly before the binding to the tree, in which you can manipulate the data; in my case I am eliciting the data out by returning the “content” of the wrapper object “d” rather than the whole thing.

   31 <script type="text/javascript">

   32     var initialData = <%= ViewData["InitialList"].ToString() %>

   33 $(function () {

   34     $("#MyTree").tree({

   35         data : {

   36             type : "json",

   37             async : true,

   38             opts : {

   39                 async : true,

   40                 method : "GET",

   41                 url : "GetNodesOfParent"

   42 

   43                 }

   44             },

   45           ondata: function (data, tree_obj) {

   51                     return data.d;

   52                 },…..

Such flexibility and clean structure in controls and API’s is one of the very important aspects a control-developer should keep in mind.

Leave a Reply

Your email address will not be published. Required fields are marked *