The Frontier Group - Blog

Keeping Context in Your AJAX Callbacks

March 13th, 2009, by aaron

These days I’m using a lot of asynchronous calls to get data and dynamically build the UI on the client side. It generally allows a far nicer experience to be provided to the user, being able to update parts of the UI without reloading the whole page is one of the first steps to your apps being able to wear a Web 2.0 moniker.

The general pattern for me these days has become :

var callback = function CallBack(data) {
    ... Do Some Processing ....
}

var input_data = GatherData();
MakeRequest(target_url, data, callback);

I tend to use jQuery and so my callback is passed in the returned data from the target_url. My call back function then generally performs some tasks on the UI based on what it receives.

The problem though is that in this pattern you can’t get any data from the context when MakeRequest() is called into the scope of CallBack. It’s a scoping issue that falls outside of this little post, but if you’d like an explanation of how Javascript handles scope of variables then you can Google for Javascript scope chain or take a shortcut to this article. Essentially when the call is made to CallBack() all it will have is it’s own variables and any globally accessible (window) variables.

This week though I had a thought and worked through it with one of my work mates, Tony. If you passed in a function that had the scope that included the context you wanted to pass, then maybe you’d be able to access whatever data from the callee you wanted. It turns out that this does work.

The way to do this is pretty simple, and I used it to create a simple function that would grab data and then populate a select element with options. In this case the context I’d like to keep is which select element is the target.

Say that I needed to run this over a bunch of select elements in quick succession then as the callbacks were issued they may end up out of the initial execution order, so the target element isn’t reliable if it’s been stored in a global variable. I could pass it in as a variable that would come back from the page that is returning the data but that just smells bad to me. I think potentially JSONP is an alternative too, but this felt like the right way.

$.getJSON(url, input_data,
	(function(target_element) {
		return function(response_data) {
			var html = [];

			for (var i = 0; i < response_data.length; i++) {
				item = response_data[i];

				html.push('');
			}

			target_element.children(':gt(0)').remove();
			target_element.append(html.join(''));
		};
	})(target_element)
);

Essentially the main thing that has changed is that we are now running an anonymous function at the time that the AJAX call is issued. This anonymous function itself returns a function that matches the signature that jQuery is expecting for the callback function. The scope in which this function runs contains the target_element because it was passed into the anonymous function as a parameter. I’m tempted to say that it’s all crazy Javascript scoping, but in reality it’s very cool and very powerful.

If you want to see the execution order of this then just put a some logging into the anonymous function and the callback function and you’ll see what I mean. It will probably make it easier to see what is going on too.

I’ve run into issues trying to get around these problems before and thankfully as mine and the team’s knowledge of Javascript increases I’m finding better and better solutions. I thought my previous method of approaching this problem was quite hacky but now I don’t feel so dirty.

Thanks to Tony too for working through this with me!

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


An Interactive Image Without Flash

January 29th, 2009, by aaron

I thought I’d just bring peoples’ attention to this awesome demonstration of what you can achieve without the use of a technology such as flash. It’s an interactive map of the marine related sites and businesses in North Carolina.

The map is implemented using jQuery and seems to pull the content for the clickable items in the map from pages within the existing CMS. This allows the content management team to update information for the map without having to know a bit of Javascript or programming in general.

The tutorial that I found this demonstration through goes into the nitty gritty of how this map was implemented.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Sexy Curls jQuery Plugin

January 19th, 2009, by aaron

I don’t know how to describe this plugin any better than in the title. It’s sexy, it makes the page curl, and it’s a jQuery plugin. I see potential uses in a lot of places, but as the author says he doesn’t want it to be that “…next annoying Javascript thing…”. I agree. jQuery Sexy Curls has the potential to make particular pages and parts of applications jump, but other than that I don’t see it taking over the world or anything.

Essentially it gives you a curl in the corner of your page that can be dragged back to reveal another ‘page’ underneath. In the author’s example the under-page is the HTML code for the example.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


jQuery Firebug Plugin

January 8th, 2009, by aaron

Debugging most things that include a jQuery chain can be annoying at best and virtually impossible at worst. Now there is a jQuery Firebug Plugin that helps when debugging Javascript that uses jQuery and it seems to do it very well! The plugin allows you to call debug(), assert(), log() or any other Firebug 1.2 call at any point in your chain. Fantastic!.

There are examples in the article of how to use jQuery.Firebug() so I suggest taking a peak.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


25 Tips for Better jQuery

December 18th, 2008, by aaron

Typically these types of “25 Tips To…” or “10 Things That…” style articles have a few good points but are filled with fluff. However the article 25 Tips for Better jQuery is full of great points that cover architecture, coding conventions, compatibility and performance.

If you are looking to get a better handle on jQuery and more importantly how to use it well, I haven’t seen many better places to start.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.


Follow Us

Stay in the Loop

  • Enter your email address to subscribe to our mailing list. You'll get updates about our products, specials and bonus offers, and general behind the scenes news from our team.

Twitter

Newsletters

Alexa Rank

Testimonial

The boys at The Frontier Group are amazing! For such a relaxed and personable organisation, they have phenomenal technical ability and a rampant professionalism. They have customisable solutions for all of my IT needs and they always deliver, on time and beyond expectation.

They fix problems other service providers can't and they helped me get a critical section of my web site up and running 10 minutes after I emailed the request!

Alex Hyndman, Nexus Car Share.

Featured Project

Case Study - Caudo Group - www.caudo.com.au

Website

www.caudo.com.au

Caudo Machinery

Caudo Group engaged our services to redesign their outdated website. We sent our photographer on-site to capture the essence of their business and turned it into a stunning web design.