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.


5 reasons why you need a CMS right now

March 4th, 2009, by fitzy

If you’re a business owner maintaining a web site (really, who isn’t these days) do you find yourself waiting days for updates to your web site to be completed? Are you constantly frustrated at the time, money and effort to interact with your web team to get things done?

Nearly every web site owner asks these questions and more. If you weren’t sure that you needed a CMS (Content Management System) or you didn’t know what one was, let me enlighten you.

Here’s 5 reasons how a CMS (like our own AuroraCMS) can benefit your business.

Timely changes

A CMS gives you the power to bring your changes to the web as fast as you can type. Changing content on the fly, updating mistakes or misinformation and uploading documents can be performed with ease.

Lower maintenance costs

Sometimes it can cost several hundred, or even thousands of dollars for a few content changes to a web site. With a CMS you can change and update as often as you like, at your convenience, for no extra cost. A CMS takes the pain and stress out of maintaining your website.

Anyone can update the content

Now you don’t need someone with web knowledge to maintain the website. As long as you have basic computer skills (word processing level), you can easily take control of your web site. A business owner, team member or secretary can take care of everything.

Site design remains intact

Using software like FrontPage can render your website a disgrace after a round of changes. A CMS prevents you from altering the sites basic template structure and graphic design. This means that you can trust anyone to change your content with a minimum of fuss.

Tired of your existing site design? Have a new template designed up and drop it right in. Your content will already be there and working.

Access from anywhere, at any time

Forget FTP programs or clunky software that only works on one computer in the office. On any computer load up the web browser and log in. Even away on business or using the laptop on the train to work you can draft up or publish an update.

Convinced? Then get in touch with us to discuss AuroraCMS today.

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.