Search code examples
javascriptbackbone.jsxmlhttprequestjqxhr

If I have a jQuery jqXHR response object, can I see if it's a response to a POST or to a GET?


This is basically what the original problem reduces to:

I have a Backbone model and I want to execute a certain action every time it saved successfully, but not after it's fetched. The cleanest and least intrusive way to do this, as I see it, would be to attach a handler to the sync event and check the XHR object: if it's a response to a GET, do one thing, and another if it was a POST.

However, looks like I cannot determine the HTTP method the jqXHR was created in response to... or can I?


Solution

  • You can override the Backbone.sync method like this :

    var sync = Backbone.sync;
    
    Backbone.sync = function(method, model, options) { // override the Backbone sync
    
                        // override the success callback if it exists
                        var success = options.success;
                        options.success = function(resp) {
                        if (success) success(model, resp, options);
                            // trigger the event that you want
                            model.trigger(methodMap[method]);
                        };
    
                        sync.call(this, method, model, options);
                    };
    

    methodMap looks like :

    var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'patch':  'PATCH',
    'delete': 'DELETE',
    'read':   'GET'
    }
    

    So in order to catch the GET/POST method all you have to do is :

    initialize: function() { // your view initialize
        this.listenTo(this.model, "GET", /* your GET callback */);
        this.listenTo(this.model, "POST", /* your POST callback */);
    }