Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping Backbone sync requests

I am writing a Backbone application, and I need to offer some feedback to users whenever a request to the server is made (annoying, I know, but I have no control over this behaviour of the application). The backend always reports an informative (at least in theory) message with every response, like

{
  "status":"error",
  "message":"something went really wrong"
}

or

{
  "status":"success",
  "message":"congratulations",
  "data":{...}
}

What I would like to understand is where to put a hook for some kind of messaging service.

One possibility is the parse() method for models and collections. To avoid duplication, I would have to put it inside some model base class. It is still a bit annoying since all models and collections have their own parse() anyway.

A more reasonable place to look would be the Backbone.sync function. But I do not want to overwrite it, instead I would like to wrap it inside some other helper function. The problem here is that I cannot find a good hook where to put some logic to be executed with every request.

Do you have any suggestions on how to organize some piece of logic to be executed with every request?

like image 662
Andrea Avatar asked Dec 21 '22 02:12

Andrea


1 Answers

Since Backbone.sync returns whatever $.ajax returns, it is easy to achieve what I want by using jQuery delegates, like this

var originalMethod = Backbone.sync;

Backbone.sync = function(method, model, options) {
    var request = originalMethod.call(Backbone, method, model, options);

    request.done(function(msg) {
        console.log(msg);
    });
    request.fail(function(jqXHR, textStatus) {
        console.log(jqXHR, textStatus);
    });
    return request;
};
like image 130
Andrea Avatar answered Dec 28 '22 05:12

Andrea