Weird Thoughts From Eric's Head

Tags - Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

"Instance Callback" with JSON?

I have seen a lot of questions lately on message boards and JavaRanch.com forum on how can I keep "OO Style of coding" with "instance callback" when working with a JSON request that we have no control over. A lot of people do not want to just call a funciton that outputs the results of a JSON request like most examples show on the net. Developers want to manipulate it in functions that deal with a sepcific object. With the cross-domain JSON request, we tend to loose this object since we are appending a script tag to the page. Sort of hard to pass a "this" object reference as a string.

So I thought I would show you a basic example of how we can call an external JSON api and have it work the way we want it too. No more loosing our object reference, no more polling for the request, and no more passing hardcoded variable names to these apis.

What I did is create a wonderful object that has an array. I call a function in this object to make a JSON request. I pass in the object, function I want to call when the response comes back, and the URL of the JSON api.

This function appends our passed in object references and callback function to this array. The JSON api calls array when it returns the response. The call() method hooks up the object reference and magically we are back in our OO world of object goodness.

Now what is the flaw in this code. Well when you look at it you can see there can be issues with the way I read the array index than append the value. So if you have a lot of requests fired at the same time, we could get that wonderful mismatch. In most cases this code should be just fine to play with.

You can get the code and see it in action here: http://www.pascarello.com/examples/JsonYahooExample.html
(Remember that the yahoo apis do have a limit so if it stops working, too many people looked at it today!)



Eric Pascarello
Coauthor of Ajax In Action
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Building Dynamic Web Pages


Nice example. What do you think of JSON?


Add a comment

Title
Body
HTML : b, i, blockquote, br, p, pre, a href="", ul, ol, li
Math Quiz 2 + 8 = (Helps stop blog spam)
Name
E-mail address
Website
Remember me Yes  No 

E-mail addresses are not publicly displayed, so please only leave your e-mail address if you would like to be notified when new comments are added to this blog entry (you can opt-out later).

TrackBack to http://radio.javaranch.com/pascarello/addTrackBack.action?entry=1152292250518