2014-02-07 57 views
0

在使用Backgrid.js和Backbone-pageable使用分页函数时,我在请求中推送自定义头时遇到问题。Backgrid/Backbone Pageable:使用GET请求的自定义HTTP头

初始请求正在使用xhr.setRequestHeader设置自定义标头正确获取数据。

如何使所有后续的请求从发送自定义头文件?

var MyCollection = Backbone.PageableCollection.extend({ 
     url: "http://api.myurl.com", 
     // Initial pagination states 
     state: { 
      pageSize: 10, 
      sortKey: "updated_at", 
      order: 1 
     }, 
     queryParams: { 
      firstPage: 0, 
      totalPages: null, 
      totalRecords: null, 
      sortKey: "sort", 
      q: "state:active" 
     }, 
     parseState: function (resp, queryParams, state, options) { 
      return {totalRecords: resp.responseData.total_count}; 
     }, 
     parseRecords: function (resp, options) { 
      return resp.responseData.items; 
      console.log(options); 
     } 
    }); 
    var mycollection = new MyCollection(); 
    var grid = new Backgrid.Grid({ 
     columns: columns, 
     collection: mycollection 
    }); 
    // Render the grid and attach the root to your HTML document 
    var $datagrid = $("#paginator-example-result"); 
    $datagrid.append(grid.render().$el); 

    var paginator = new Backgrid.Extension.Paginator({ 
     collection: mycollection 
    }); 
    var myCustomRequestHeader = "ABCDEFG"; 
    // Render the paginator 
    $datagrid.append(paginator.render().$el); 
    mycollection.fetch({reset: true, beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader); }, type: 'POST'}); // This works as expected, the custom header is set in the first request 

在此先感谢!

编辑,基于以下约翰·摩西的答案,这是工作片段:

var MyCollection = Backbone.PageableCollection.extend({ 
    ... 
    sync: function(method, model, options){ 
     options.beforeSend = function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader);}; 
     return Backbone.sync(method, model, options); 
    } 
... 
}); 

回答

1

覆盖MyCollection的的同步方法:

var MyCollection = Backbone.PageableCollection.extend({ 
... 
sync: function(method, model, options){ 
    options.beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader); 
    return Backbone.sync(method, model, options); 
} 
... 
}); 
+0

真棒,非常感谢。 – Monty

+0

@Monty请不要将您的解决方案添加到答案中,将它添加到您的问题。 –