[Django]-Why `init` of shim in my require.js configuration not called?

6👍

Looking at the annotated source, I see that Backbone calls define when it detects it is running with an AMD loader. Using a shim with a module that calls define results in undefined behavior because shim is for modules that do not call define.

You could achieve what you want with a fake backbone module like this which you’d save in a file named backbone-glue.js:

define(['backbone'], function (Backbone) {
    var originalSync = Backbone.sync;
    Backbone.sync = function(method, model, options) {
        options.beforeSend = function(xhr) {
            xhr.setRequestHeader('X-CSRFToken', window.csrf_token);
        }
        return originalSync(method, model, options);
    };

    return Backbone;
});

And then you should have a map like this in your configuration for RequireJS:

map: {
     '*': {
          backbone: 'backbone-glue'
     },
     'backbone-glue': {
          backbone: 'backbone'
     }
}

What this does is that everywhere (*) when the module backbone is required RequireJS loads backbone-glue instead. However, in backbone-glue, when backbone is required, then backbone is loaded. This allows backbone-glue to load the original Backbone.

👤Louis

Leave a comment