Association between Backbone Collection and XHR object created when fetching

梦想的初衷 提交于 2019-12-11 08:22:15

问题


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.



来源:https://stackoverflow.com/questions/21919690/association-between-backbone-collection-and-xhr-object-created-when-fetching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!