thatidiotguy
thatidiotguy

Reputation: 8991

JQuery Code Duplication for AJAX Calls

Original AJAX code with no JQuery. Note the definition of someVar at the very beginning.

req.onreadystatechange = function() {
        if (req.readyState == 4) {
                        //CODE HERE
                        var someVar = ....
                        //method() should be called when AJAX call returns
                        someVar.method();
                        if (req.status != 200) {
                            // error code
                                someVar.doSomething();
                        } else if (req.responseText) {
                            //other code
                                someVar.doSomethingElse();
                        } 
                    }
                };
                req.send(null);

My best attempt at JQuery. Note the code duplication:

$.get(url)
    .done(function(data){
        var someVar = ....
        someVar.method();
        someVar.doSomethingElse();
    })
    .fail(function(){
        var someVar = ...
        someVar.method();
        someVar.doSomething();
    });

Is there anyway to run code BEFORE done and fail (which is why always doesnt work in this case)?

Upvotes: 1

Views: 75

Answers (1)

Bubbles
Bubbles

Reputation: 3815

Looking at the jqXHR documentation, done, fail, always and then should be invoked in the order they are registered - have you tried putting the shared code in an always before the other functions?

Here's a jsBin showing this in action; just be sure to leave the console open.


EDIT

This is a bit gimmicky, but if you're really deadset on not having a variable in the parent scope, there is some degree of shared context between the functions you can use. A jQuery ajax request is it's own object, and as such you can share data on this object between calls on it.

So, you could share the code like so:

$.get()
  .always(function() {
    this.someVar = ...
    this.someVar.doMethod();
  }).done(function() {
    this.someVar.doneFunction();
  }).fail(function() {
    this.someVar.failFunction();
  })

If you were to do this though, I'd be a bit more cautious with my variable conventions - probably would try to prefix someVar with something application-specific (like myApp_someVar).

Upvotes: 2

Related Questions