tags:

views:

47

answers:

2

If you've written a class in JavaScript that calls a remote service's API, and that remote API offers a callback, how do you get the response back into the instance of the object that made the request?

I'll try to give you a very basic example FOO for making cross domain calls to BAR service which offers a callback. Please ignore the usual security concerns, (I own both servers).

function FOO() {
    this.response = null;

    this.execute = function(url) {
        var script = document.createElement('script');
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script); 
    }

    this.catch = function(response) {
        this.response = response;
    }
}


var sample = new FOO();

sample.execute('http://barservices.com/sample/?callback={ plshelphere: this.catch}');

I have a way to make this work, but I'm curious if there is an "accepted approach" here.

Anyone have thoughts for me?

A: 

I dunno if I understand 100%, so let me double check:

  • You want to write a custom JavaScript object/class.
  • It should serve as a facade to encapsulate the logic of communicating with a remote Web Service.
  • This service is on a different domain.

But I don't follow why you create a element. Why aren't you instead using an 'Xml Http Request?'

Nonetheless, I'd recommend some reading about the Ajax Proxy "Pattern":
http://www.springerlink.com/content/mn623501w3h0n166/
http://ajaxpatterns.org/Cross-Domain_Proxy

... and the GoF Facade Pattern
http://en.wikipedia.org/wiki/Facade_pattern

LeguRi
XmlHttpRequest doesn't work across domains.
AnthonyWJones
Hence the Ajax Proxy "Pattern" :)
LeguRi
A: 

As long as sample is declared in the global namespace you could just use:

sample.execute('http://barservices.com/sample/?callback=sample.catch');

If not then, there are a few other options. You could setup a global set of callbacks and add a new one to it ala http://gist.github.com/110884 You could use a framework that has functions for this sort of thing(jQuery et al)

If your service doesn't care what your function looks like, you could pass it a bare function.(twitter strips this stuff out).

(function(){alert('I work')})
BaroqueBobcat