0

I want to build a javascript class which I initialize and will make only one ajax request to save some data off so I can do stuff with it aftewards. It is important that there is only one request for performance reasons.

Here is the initialisation

var web = new webService();
web.connect(app.info);
web.info();

and this is my class

function webService() {

    this.d = new Object;

    this.connect = function(app) {
        console.log(app);

        $.ajax({
            url: 'my working url which gives me my jsonp object',
            dataType: 'jsonp',
            jsonp: 'jsoncallback',
            timeout: 5000,
            success: function(data) {
                this.d = data;
            },
            async: false
        });
    }

    this.info = function() {
        console.log(this.d);
    }

}

I was wondering if there might be a problem with synchronizing? I'm not sure so I wanted to ask you guys.

Jeff B
  • 8,572
  • 17
  • 61
  • 140
upplex
  • 91
  • 1
  • 3

3 Answers3

3

jQuery $.ajax (and similar methods, like $.getJSON()) will return a Deferred object. Like other JavaScript objects, this is a "thing" which you can store in a variable and pass around in your code. Then you can add (async) callbacks to it at any time:

// Don't include a 'success' callback yet.
$def = $.ajax(...);
// $def is an object which you can store globally 
// or pass as an argument into other functions.
//
// Somewhere else, add a success callback:
$def.done(function(data) {
   // ...
});

See http://api.jquery.com/category/deferred-object/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
1

If you refactor your code to return a deferred object thus:

function webService() {

this.d = new Object;

this.connect = function(app) {
    console.log(app);

    return $.ajax({
        url: 'my working url which gives me my jsonp object',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data) {
            this.d = data;
        }
    });
}

this.info = function() {
    console.log(this.d);
}

}

You can then use done:

var web = new webService();

web.connect(app.info).done(function() {web.info();});

this also means your A jax is asynchronous, like it should be.

You could argue if your going down this route though, what is your function webservice even doing. Why not just let deferred do all the work?

Liam
  • 27,717
  • 28
  • 128
  • 190
0
this.connect = function(app) {
    console.log(app);
    var that = this;  //store this into a variable

    $.ajax({
        url: 'my working url which gives me my jsonp object',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data) {
            that.d = data;  //use that so you have the right scope
        },
        async: false
    });
}

other option is to use bind or jQuery's proxy

epascarello
  • 204,599
  • 20
  • 195
  • 236