Big Bang Technology

Sun 15 Mar
2009

Using Prototype to Inject Custom Class Instances into the DOM

Posted at 1:31 PM by Cameron Westland in Tutorials

I've been using the Prototype Javascript Framework more than usual recently to develop some fancy reports for a client. I'm going to share a simple technique that involves using toElement on a class as an easy way to insert it into the DOM.

Requirements

The Story

A few weeks ago, Max asked me to put his twitter feed on our website. I said no – Twitter does a good job at displaying Twitter content. This got me thinking, however, that other people would want to do the same thing. Also, since Twitter is the new Hello World, this serves as a good example. I've built Max his javascript driven twitter feed. Take a look first, and then we'll talk about what we're doing here.

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.

Recap

  • 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.
  • ???
  • Profit!

References