how to set backbone fetch callback method

2019-07-17 02:25发布

问题:

How do you set the jsonpCallback function name for the fetch method of backbonejs? To add to the problem is I also using requireJS so i am trying not to have a global function and follow the AMD pattern.

The reason I can't use the auto generated method name from jquery is the developer of the api I am using want's to have a static name of for the callback method for caching reasons.

Sample Code

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'paginator',
    'models/item'], function($, _, Backbone, Marionette, Paginator, modelItem) {
    'use strict';

        var PaginatedCollection = Paginator.requestPager.extend({ 
            model: modelItem,

            paginator_core: {
               jsonpCallback : 'callbackFunc',

                type: 'GET',
                cache: true,

                dataType: 'jsonp',

            },      
            callbackFunc : function(data) {
                console.log(data);
            }

        });

        return PaginatedCollection;

    });

Error Message

TypeError: callbackFunc is not a function

回答1:

Override your fetch to pass the callback method name in the request.

fetch: function(options) {
  options || (options = {});
  var data = (options.data || {});
  options.dataType = 'jsonp';
  options.jsonp = 'callbackFunc';

  return Backbone.Collection.prototype.fetch.call(this, options);
}


回答2:

Since you want to cache the results (in the browser, and maybe on the server as well) you also need to set options.cache param.

Also the param is jsonpCallback not jsonp

Here's what your sync over-ride function should look like:

sync: function (method, model, options) {
    options.timeout = 10000; // required, or the application won't pick up on 404 responses
    options.dataType = 'jsonp';
    options.jsonpCallback = 'callbackFunc';
    options.cache = 'true';
    return Backbone.sync(method, model, options);
}

NB: BackboneJS v1.0, not tested in 0.9 or earlier