Association between Backbone Collection and XHR object created when fetching
Asked Answered
R

1

1

Is there an existing association between a Backbone Collection and the XHR object created when you execute a .fetch() on it?

I would like to do something like this:

collection = new Backbone.Collection;
xhrObj = collection.fetch();
xhrObj.parent == collection; //true

The larger goal is for me to check to see if there are any pending .fetch()'s for a specific collection. If there is another way to do this in Backbone, please let me know. I figured I would just store XHR objects and check if any of the ones that have not finished are associated with the collection.

Ruffi answered 20/2, 2014 at 21:11 Comment(0)
T
0

You can do it like this :

var fetch = Backbone.Collection.prototype.fetch;
Backbone.Collection.prototype.fetch = function (options) {

    options = options ? _.clone(options) : {};

    var success = options.success;
    options.success = function (collection, resp, options) {
        collection.xhrObj = resp;
        if (success) success(collection, resp, options);
    };

    var error = options.error;
    options.error = function (collection, resp, options) {
        collection.xhrObj = void 0; // or whatever you want
        if (error) error(collection, resp, options);
    };

    fetch.call(this, options);
};

after that, if the fetch call succeeded you can find the server response in your collection.

Tephra answered 21/2, 2014 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.