indieisaconcept
indieisaconcept

Reputation: 263

Overriding underscore.js defaults when used with require.js as an AMD module

Since underscore is loaded in as an AMD module does anyone have an recommendations on how best to set global options against underscore so that I can still access it under the same unified module name and have my overrides available.

I've played around with it and so far I basically have a wrapper in which I include underscore as a dependancy, make my modifications and then return the modified underscore.

paths: {
    'underscore': 'libs/underscore/1.2.3/underscore',
    'underscore-override': 'libs/underscore/define'
}

Inside define.js I basically have the following:

define(['underscore'], function (_) {

    // use mustache syntax
    _.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g
    };

    return _;

});

This approach works but I'm sure there is a much more elegant way to achieve this so that I don't have to use 'underscore-custom'.

Any suggestions?

Cheers :-)

UPDATE: Based on the suggestions in the accepted answer I now do the following:

libs/bootstrap.js

define([
    // add custom library defines here
    '../libs/underscore/define'
], function () {

    var libs = [].slice.call(arguments),
        initialize = function () {
            libs.forEach(function (lib) {
                if (typeof lib === 'function') {
                    lib();
                }
            });
        }

    return {
        initialize : initialize
    }

});

libs/underscore/define

define(['underscore'], function(_) {
    return function () {    
        // add custom settings here
    };
});

main.js

require(['libs'], function(libs){
    libs.initialize();
});

Upvotes: 1

Views: 1571

Answers (1)

Thomas Davis
Thomas Davis

Reputation: 1896

You could possibly have a configurator module that loads in anything that needs to be configured.

define(['underscore', 'jquery'], function(_, jQuery){
  var setUp = function(){
  // Underscore Configuration
  _.templateSettings = {};

  // jQuery Configuration
  $.someplugin = {};
  };
  return { setUp: setUp }; // or something like that
});

//main.js
define(['configurator'], function(config){
  config.setUp();
});

Upvotes: 2

Related Questions