Backbone.js parses an unmodified response

I have a server that works with the ETag header. The highway refers to the API for the first time: everything is fine, the response received and analysis. The second time: the trunk sends to the ETag server, in response receives NotModified. And Backbone is trying to analyze this answer, as a result of this we get a collection called reset.

Is there a way to reset the collection?

The method of adding options to add to the selection method will not work. Since I need to completely update the collection if I came to the server response.

var recommendCollection = Backbone.Collection.extend({
    model : Event,
    etag : null,
    urlRoot : '/api/users',
    initialize: function() {
        this.etag = null;
    },
    parse: function(response) {
        return response.data;
    },      
    url : function () {
        return (this.urlRoot + "/"+window.me.get('id')+ "/recommendation");
    },
    beforeSend : function (jqXHR, settings) {
        jqXHR.setRequestHeader('if-none-match', this.etag);
    },
    complete : function (jqXHR, textStatus) {
        if (jqXHR.status == 200 || jqXHR.status == 304) {
            this.etag = jqXHR.getResponseHeader('ETag');
        }
    },
    update : function () {
        this.fetch({
            beforeSend : this.beforeSend.bind(this),
            complete : this.complete.bind(this),
            data : {
                cityId : window.me.get('cityId'),
            }
        });
    }
+5
source share
2 answers

As far as I can tell, there is no simple solution to capture answer 304. What I came up with:

  • parse , options, , . , reset

    parse: function(response, options) {
        if (options.xhr.status === 304)
            return this.models
    
        return response.data;
    }
    

    http://jsfiddle.net/nikoshr/sxv9P/12/

  • jQuery ifModified,

    ifModified : false

    , . Last-Modified . - false, . jQuery 1.4 "etag", , .

  • fetch , 304

    fetch: function(options) {
          options = options ? _.clone(options) : {};
          if (options.parse === undefined) options.parse = true;
          var collection = this;
          var success = options.success;
          options.success = function(resp, status, xhr) {
            if (xhr.status!==304)
                collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
            if (success) success(collection, resp);
          };
          options.error = Backbone.wrapError(options.error, collection, options);
          return (this.sync || Backbone.sync).call(this, 'read', this, options);
    }
    

    http://jsfiddle.net/sxv9P/1/

+8

304 . , , .

+1

All Articles