how to set backbone fetch callback method

佐手、 提交于 2019-12-11 04:07:31

问题


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



来源:https://stackoverflow.com/questions/15937812/how-to-set-backbone-fetch-callback-method

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