iphone: deli.cio.us/tags/iphone
Development
JavaScript
code
html
webdevelopment
Articles
article
Davey Waterson of the Aptana Jaxer team has posted an article on using jQuery on the server-side with E4X and more that shows an example of server-side Ajax with a popular framework.
The article describes a polling application that features:
There are fun little features such as nuking portions of the page if the permissions call for it:
Since the application delivers no JavaScript itself, this would all work even if the user has JavaScript turned off, on a simple mobile phone, etc.
Composing DSLs in JavaScript is James Coglan's latest perusal into fun with JavaScript and DSLs.
He walks through the building of this DSL in a step by step manner. He uses his JS.Class library, but you could of course substitute your favourite JavaScript library.
Because JavaScript is the language of the web browser, and because the web browser has become the dominant application delivery system, and because JavaScript isn't too bad, JavaScript has become the World's Most Popular Programming Language. Its popularity is growing. It is now being embedded in other applications and contexts. JavaScript has become important.
Douglas Crockford got to act all curmudgeonly as he talks on how The World's Most Popular Programming Language Has Fashion and Luck to Thank.
He starts out talking about the black art of languages:
The art in language design is knowing what to leave out. The features of a good language work together harmoniously. A good language helps us to better understand a problem and to find the best expression of its solution.
A good language is composed of a limited set of features. But there is little agreement on which features are best. Programmers can argue endlessly about features and whether a set of features makes one language better than another. Features matter, but we just don't understand yet how they matter.
Language design has more to do with fashion than technology. It may seem strange that fashion is a major factor in the nerdliest of arts, but it is true. A language with radically different syntax, for example, has no hope of finding broad adoption, regardless of the brilliance of its design. This tends to constrain the rate at which languages evolve.
Just like fashion, a programming language is often a product of its time. The deep problem in language design is not technological, it is psychological. A programming language should equip us with structures that help us to reason more effectively.
And then he gets to JavaScript itself, and how it has managed to become the most deployed language in history even with its foibles.

Neil Roberts has posted a great article on Creating Your Own $ with Dojo:
The bling, one of the best global variables in JavaScript. A tool which has come to mean, as a function, a way to locate a node or set of nodes. And, as a namespace, a simple way to access often-used functionality. "This can't be done with Dojo," you insist. But you're wrong, it's really easy. The ideas behind this little symbol are quite simple and I'm going to show you how to create your own customized version of it.
He manages to walk us through a path where he gets $ working in a way that mimics jQuery. He starts with $ = dojo.query; and ends up with:
He then tackles plugins and using:
You end up being able to do:
Very cool indeed!
"agrath" has developed a very nice Canvas example using Prototype that makes use of a common Prototype-isms: Object.extend, Class.create, bind, enumerables, $w, $.
The Polar Clock is a different visualization of time and the example walks through all of the work required to implement it using Prototype 1.6.0.2 and Canvas, including the draw method:
The article walks through a lot of Canvas as well as the Prototype side of things. Very thorough.
Peter Michaux has done some very thorough work on feature detection in the browser and cross browser widgets.
In his feature detection article he walks through a myriad of approaches with pros and cons:
Feature testing is not easy and there is no one right answer. From a practical stand point, the more strict your tests are the more likely your code runs only when it will run successfully.
There are some obvious wrong answers like
navigator.UserAgentinference, unrelated execution inference and unrelated object inference. Check the library you are using. Does it use any of these techniques? I have seen many uses of these techniques in mainstream libraries even where there is a well known, better test available. The mainstream libraries cannot consider claiming to be state of the art until they remove these bad practices at the very least.The above discussion focuses on tests against a single object to infer if that object or similar ones work. Sometimes it may be necessary to use multiple objects together to make an inference about one object. An example for scroll reporting. Even when using multiple host objects in a test the three
isHost*functions will be useful.Feature detection is not easy, but as professionals, we should use the best tests we can.
In his cross browser widget article he goes further to create a library to handle cross browser widgets:
Build a robust widget for the general web is hard work and the example above has room for improvement. The level of feature testing could be increased at the cost of file size. For example, on comp.lang.javascript, David Mark suggested that the browser could run out of resources and a call to createElement could return null. He also admitted this may be overly paranoid. I think it is and by testing for the existance of document.createElement I've inferred that calls to it will work as expected.
I've tried the tabbed pane in all the browsers I have and it is either enabled an works or it is disabled and doesn't throw errors. I suspect there is a browser out there somewhere that will throw an error. That is just the nature of the cross-browser challenge. In a perverse masochistic way, I somewhat hope someone can find a browser in which this widget breaks. That is one way we can continue to improve.
Colin Morris, author of Y-Validator, has written a piece on JavaScript: It's Just Not Validation! which discusses JavaScript validation, and "input assistance":
JavaScript input assistance, when built separately from back-end validation, is not ideal. At worst, the two piece of functionality work differently, and what's valid on the client side isn't valid at the server. At best they work fine -- initially. But with validation logic in multiple locations, there's an increasing likelihood that only one will get updated when changes are required, at which point we get inconsistent results.
Finally, back-end validation is required. JavaScript assistance is nice.
The use of a central object to manage both the validation and input assistance tasks creates a consistent end user experience even with JavaScript disabled.
- We have one place to update both the enhancement (JavaScript assistance) and the required functionality (back-end validation). Therefore, the two can't get out of step, and we can ensure a seamless experience for the user.
- We have one place to find the enhancement, so it's less confusing for future maintainers of our code to located the points at which various validations and assistances are implemented in the code.
- The code also promotes the separation of behaviour from presentation. The programmer programs the validation and the designer implements the presentation of the feedback.
- The user feels in more control, having confidence in hitting the big submit button.
Don't forget: the code for the PHP-Validate and a sample form is available for download.
Java and JavaScript share the first four letters of their name, and have an entangled past. Joe Walker has an interesting little take on the evolution of the languages that shows some mirror images such as:
It's interesting that the current simple version of JavaScript already has the features (i.e. closures) that people want to keep out of Java otherwise it will become too complex, and that Java already has some of the features (i.e. classical inheritance) that people want to keep out of JavaScript, otherwise it will become to complex.
And some thoughts on JS2:
With JavaScript, people see a neat, compact language and fear it turning into Java. The good news is that it won't fully turn into Java because JavaScript already has closures and no one thinks they should be taken out ;-) The danger of the "features over complexity" argument, is that it can be applied indiscriminately, creating a monster, and the fear is that JavaScript will become a monster.
I'm gradually coming round to the opinion that many of the changes proposed to JavaScript actually reduce complexity. There are nearly as many frameworks that add classical inheritance to JavaScript as there are Ajax frameworks. Having one solution that we can all agree on can't be a bad thing even if you prefer prototypal inheritance.
Some like to DOM their way around. Others prefer the simplicity of innerHTML. Julien Lecomte, of Yahoo!, wrote up his thoughts on the problems with innerHTML.
Julien first points out some issues:
He then puts together Douglas Crockfords purge and some code to clean up script tags, arriving at:
Rakesh Pai has written up a piece on GData JavaScript client library (video), CrossSafe, and SubSpace.
He discusses the high level, and then delves into the requirements and process for getting cross domain code working:
Here's what you require to get cross-domain read write JavaScript APIs to work.
The "setup" required at the client's end is that he should have at least one static cacheable resource embedded in the page where he's consuming the API, which is loaded from the same domain as his page. This could be in the form of a static CSS file, or an image. If the page doesn't have either, it will be required to insert one – maybe in the form of a 1px image hidden away by using inline style attributes. This is usually not too much to ask for, considering that pages are either made up of spacer GIFs or CSS documents, usually loaded from within the same domain. The static resources I mentioned could even be from a different sub-domain within the same domain, but it might complicate scripts slightly to have it set up that way. If this setup is not possible at all (oh, come on!), you could still find a work around2, but I think that this is the easiest way to get things up and running.
You will need to do some setup at your end, if you are the creator of the API. In particular, you will need to setup a "proxy" page that intercepts the requests from the JavaScript client API, conditions the data, and passes it along to the REST API. This proxy page also reads the response from the REST API, conditions the data to suit the client, and flushes it down to the JavaScript.
Now, let's go over the process of actually orchestrating the communication.
The API client library is included on the page by means of a script tag pointing to your domain (your domain being the host of the client library). This is similar to including the Google Maps API on the page.
Once included, the script scans the page for the static resource mentioned above. This is done by walking the DOM looking for
linkorimgtags, and checking the value of thehref/srcattribute to ensure it lies within the same domain as the calling page. The URL of this resource is stored for use later. At this point, if required, the client library can signal to the developer that it is ready for communication with the server. If the resource is not found, the client-library should throw an error and terminate.When a request requires to be made, the client library takes the request parameters and prepares the markup for a form. This form can have any
methodattribute value, and should have it'sactionattribute set to the proxy page on your domain. The parameters to be sent to the server should be enumerated as hidden fields within the form. The client library also specifies the resource (in a RESTful sense) that needs to be acted upon. Also, the name of the static resource we had hunted down earlier is passed on to the server. This form is not appended to the document yet. This markup is then wrapped into<html>and<body>tags. The body tag should haveonload=”document.forms[0].submit();”.The client library then creates a 0px x 0px iframe, without setting the
srcattribute, and appends it to the page's DOM. This makes the browser think that the iframe exists in the same domain as the calling page. Then, by using the iframe document object'sopen(),write()andclose()methods the markup created in the previous step is dumped into the iframe. As soon as the close method is called, the form gets submitted to the proxy page on your domain because of theonloadin the body tag. Also note that this gives the server access to any cookies it might have created from within it's domain, letting you do things like authentication. In this way one part of the communication is complete, and the data has been sent to the server across domains. However, the iframe'sdocument.domainhas now switched to point to your domain. The browser's security model now prevents any script access to most parts of the iframe.The proxy page sitting on your server now queries your REST API – basically doing it's thing – and gets the response. Response in hand, the proxy is now ready to flush the response to the client.
If the response is rather large in size, as might be the case with a huge GET call for instance, the proxy breaks it up into chunks of not more than say 1.5 kb2.
The proxy is now ready to flush the response. The response consists of iframes – one iframe for each of these 1.5 kb chunks. The iframe's
srcattribute is set to the static resource we had discovered earlier. It is for exactly this purpose that we had hunted the resource down and passed on the URL to the server. At the end of each of these URLs, the proxy appends one of the chunks of the response, after a “#” symbol, so that it works as a URL fragment identifier. Also, the iframe tags are each given anameattribute, so that the client script can locate them.Meanwhile, the client-side code is where it had left off at the end of step 4 above. The script then starts polling the iframe it created to check for the existance of child iframes. This check of iframes will need to based on the iframe name the server will be sending down. It will look something like this:
window.frames[0].frames[“grandChildIframeName”]. Since the static resource we have loaded into the grandchild iframe is of the same domain as the parent page, the parent page now has access to it, even the intermediate iframe is of a different domain.The client script now reads the
srcattributes of the iframe, isolates the URL fragments (iframe.location.hash), and reassembles the data. This data would typically be some JSON string. This JSON can then be eval'd and passed on to a success handler. This completes the down-stream communication from the server to the client, again across domains.With the entire process complete, the client-library can now perform some cleanup actions, and destroy the child iframe it created. Though leaving the iframe around is not a problem, it is not necessary and simply adds to junk lying around in the DOM. It's best to get rid of it.
Andrew Dupont has written a tutorial on how to normalize proprietary browser events using Prototype's new custom events feature.
The piece is interesting as it talks about how the Prototype core team originally went down the wrong path trying to boil the ocean with great features that were a bit too much. And then:
we refocused, trimmed the fat, and added a whole bunch of features to the event system while still excluding thie kitchen sink. We picked some low-hanging fruit; for instance, we normalized the event object so that properties like target exist in all browsers, and we ensured events fire in the scope of the element in IE (so that this refers to the proper thing).
But we also added cross-browser support for custom events. Now developers can fire their own events alongside native browser events and can listen for both types with the same API. Custom events will make Prototype add-ons at least 50% more righteous, allowing for even more control than the standard callback pattern. Imagine TableKit firing an event when a cell gets edited, or PWC firing an event when a dialog is resized.
Since the 1.6 RC1 release, several people have asked whether we have any plans to add native support for mouseenter, mouseleave, or mousewheel. I think we ought not, lest the event codebase become an unholy thicket of special-casing. That’s the sort of environment where bugs thrive.
But, as Sam points out, the addition of custom events makes it easy for third parties to add their own support for proprietary browser events. To demonstrate, today we’ll write 20 lines of code to add sane, cross-browser support for mouse wheel events.
I’m calling these pseudo-custom events because they serve the same purpose as standard browser events: they report on certain occurrences in the UI. Here we’re using custom events to act as uniform façades to inconsistently-implemented events. Together we’ll write some code to generate mouse:wheel events. At the end of this article, you’ll know enough to be able to write code to generate mouse:enter and mouse:leave events document-wide.
This leads you into the example itself which takes you through a number of iterations before ending up with: