Making JavaScript APIs Easier to Use

Todd Anglin presented some of the AJAX functionality available in ASP.Net 4.0 at this months ADNUG meeting. One of the things he demonstrated was the Client Side binding, which is really cool (I’ll have more on this later). In one of his code samples, he showed how the MS AJAX library call to bind an element to a datasource. It looked odd to me at first and and I couldn’t figure out why at first. Then on the way home, I realized that it designed completely wrong for a JavaScript function. The function call looked something like this (I may not get this syntax completely right,it’s just an example, please don’t sweat the details).

$create(Sys.Data.DataView, {}, {}, $get(‘identifier’));

It’s a fairly simple method call. I haven’t studied the details, so I don’t know exactly what all of the parameters do. It looks like the first parameter is the data type, the second and third are a set of options we don’t need in this example, and the last parameter is the id of the element we want to databind. So what is wrong with this? I am needing to declare a lot of function parameters I don’t need for normal operations. It looks like an overload with just the element to databind would be what I would use for common usage.

One of the cool parts in JavaScript is that I don’t need to actually overload the method. I can call the method with just the first paramter and the others will be null. I can deal with this possibility be creating aliases that have default values if they are null. The shortcut syntax looks like this.

Now I could also use the method like this, even further reducing my cognitive load

$create(‘identifier’);

JavaScript has tons of little features like these that can make really fun to use when the API designers take full advantage of what it has to offer. Of course it does have it’s share of “bad” features too. A great API is one that knows the differences.

Thanks for coming to the session. As a side note (which I’m sure you may already know), the $create function is actually provided by the base MSFT Ajax library introduced with ASP.NET 2.0 Extensions. It’s a shortcut for Sys.Component.create and it has a signature that looks like:

$create(type, properties, events, references, element)

Only “type” is required (in theory), but I agree that it probably would have made more sense to put “element” second in the list since it is used often without init values. Hope that helps clarify the source and format of that method.