-->

Association between Backbone Collection and XHR ob

2019-07-25 16:50发布

问题:

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.

回答1:

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.