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});Written by Tyler Mauthe
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#