Last Updated: February 25, 2016
·
457
· tylermauthe

Best Way to Override Default Configs using jQuery

Very often in JavaScript you find yourself needing to have a bundle of related configuration details, especially when making plugins.

Typically these bundles of values are stored in a plain-old JavaScript objects, but how can we easily set up defaults? Many modern JS utility libraries come with an extend function -- which merges two objects.

Below there is a fairly real-world example of how to use jQuery's extend functionality to reliably override a set of default configuration values with values passed in from the user.

jquery.thingify.js - defining the plugin

// Some fancy jQuery plugin boilerplate
// ...
$.fn.thingify = function(config) {
  var defaultConfig = {
    widgetness: true,
    porpoise: 'blue',
    realityHandler: $.noop
  };
  var setupConfig = $.extend(true, {}, defaultConfig, config);
  setupTheThing(setupConfig);
}
// ... more plugin magic

myAppInit.js - using the plugin

// default usage
$('.widget').thingify();
// overriding
$('.widget').thingify({porpoise: 'grey', realityHandler: enlightenedStateHandler});