Search code examples
javascriptbackbone.jsmodulerequirejsmarionette

How to override a vendor library with requirejs


I use the Marionette.js framework and I need to override a function of the Marionette.TemplateCache module but without update the marionette.js file. So, I've created a new module for this :

    define(['marionette'], function (Marionette) {
    'use strict';

    _.extend(Marionette.TemplateCache.prototype, {
        loadTemplate: function(templateId){

            var template = templateId;

            if (!template || template.length === 0){
                throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
            }

            return template;
        }
    });
    return Marionette;
});

But, I don't know how to configure my requirejs main, for when I load the Marionette.js framework , my module override Marionette.js.

Have you got any ideas how to do this?

Thanks.

Jonathan.


Solution

  • You can rename the path defined for original library to something like marionette-core and update your module as follows

    define(['marionette-core'], function (Marionette) {
    'use strict';
    
       _.extend(Marionette.TemplateCache.prototype, {
        loadTemplate: function(templateId){
    
            var template = templateId;
    
            if (!template || template.length === 0){
                throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
            }
    
            return template;
        }
      });
    
      return Marionette;
    });
    

    now define a path to your module as marionette.

    So now when you require marionette, require.js will load original marionette and return your customized instance.

    Plus you can still load original library using marionette-core somewhere else if necessary