Backgrid/Backbone Pageable: Пользовательские заголовки HTTP с запросом GET

У меня возникают проблемы с отправкой пользовательского заголовка в мои запросы при использовании функций пейджинга с Backgrid.js и Backbone-pageable.

Первоначальный запрос правильно извлекает данные с пользовательскими заголовками, установленными с помощью xhr.setRequestHeader.

Как сделать так, чтобы все последующие запросы от backgrid также отправляли собственный заголовок?

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);
    }
...
});

person Monty    schedule 07.02.2014    source источник


Ответы (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);
}
...
});
person John Moses    schedule 07.02.2014
comment
@Monty, пожалуйста, не добавляйте свое решение к ответу, добавьте его к своему вопросу. - person Bill Woodger; 07.02.2014