Getting the Data
After quickly scanning the Twitter API Wiki, I found out that we can use JSONP to load our data. Since we can't directly load the data from Twitter via XMLHttpRequest we have to embed a script tag with the query. Fortunately we can specify a callback function so that when the data is returned, it will fire the function, passing the data loaded from the server to it as an argument.
Once we get the data back we iterate through each of the result items and create a new instance of the Tweet class for each one. We then insert the instance directly into the DOM. As you can see on the sample page the class is magically rendered on the screen. This is because Prototype automatically calls toElement on our class.
What's in the Tweet Class?
This class is very simple. In the constructor it saves the data from the server in instance variables that it will later use in the rendering process (see documentation for details on what gets returned). Next, there is an instance method named toElement. In Prototype, whenever a class instance is passed to any of the insertion methods – Element#insert, Element#update etc. – it looks for this method on the class. Keep in mind that Prototype expects an HTML element or a String to be returned from this instance method.
- Construct a class passing key information into the constructor
- Maintain a reference to the class manipulating it in memory without worrying about DOM
- Feed it to one of Prototype's element insertion methods just like you would any other HTML element.