23 August 2011

Listing event handlers tied to DOM elements with jQuery and Firebug

I'm busy hacking a template from an existing source to fit into a new Cake backend.  The template is pretty well written but I need to update the way in which content is being loaded and displayed.  Currently the site loads the *entire* site into one page and then flipping the visibility of elements in order to simulate dynamic loading.  Of course this works fine for the demo site the template loads, but is not going to fly for a production site.

I ran into the problem of having to work out where the event handlers are being declared for various elements on the page.  I was faced with the task of trekking through 15 files of Javascript.  Okay some are obviously not candidates (like jQuery.js itself) but that's still a mission.

Luckily jQuery has an extra bit of goodness that made the task trivial.  It stores event handlers in the data attribute (read up about that here http://api.jquery.com/jQuery.data/ ).

Using Firebug you can open your console tab and bash in the magic command:


replacing the element selector with something more likely to match in your document.

That will give you a nice interactive way to explore the element and all of it's handlers, letting you click through right to the point in script where the handler is defined.

This saves lots of time having to RTFS.

17 August 2011

Caching your Twitter feed on your website in PHP

Instead of reinventing the wheel I'm going to copy the script found at css-tricks.com (click here)
function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";

$xml = simplexml_load_file($url) or die("could not connect");

       foreach($xml->status as $status){
       $text = $status->text;
       echo $text;

//my user id kenrick1991

I'm leaving the original author's Twitter ID in there, but obviously you'll change this to yours.

This function will retrieve the most recent Tweet from your feed (see the "count=1" variable in the URL). But it will request this every time the page loads.

The most simple caching strategy is to write your Twitter status to disk, and when your page loads check the timestamp of the file against the value returned by time(). If it exceeds whatever threshold you deem appropriate you can reload the feed from the web.

Rather than boring you with code that demonstrates the use of file_exists(), filemtime(), and file_get_contents() I'll save you a Google search by highlighting the way to serialize and deserialize a simplexml object so that it is suitable for writing to disk (or database).

Here's a routine to dump the Twitter simplexml object to disk:

private function updateCache() {
        $xml = $this->xml->asXML();
        $handle = fopen($this->cacheFile,'w');
        fwrite($handle, $xml);

And here is how to retrieve it:

$xmlCache = file_get_contents($this->cacheFile);
$this->xml = simplexml_load_string($xmlCache);