I am having the following plugin:
(function($) {
$.fn.myPlugin = function(options) {
var opt = $.extend({}, $.fn.myPlugin.defaults, options);
if (!opt.a) {
console.log('a is required!');
return false;
}
if (!opt.b) {
console.log('b is required!');
return false;
}
if (!opt.c) {
console.log('c is required!');
return false;
}
//Rest of the logic
}
$.fn.myPlugin.defaults = {
};
});
Now this plugin will be called from outside like this:
$('div.x').myPlugin({
a:'aa',
b:'bb',
c:'cc'
});
As you can see from the plugin I need a, b and c options from outside i.e they are compulsory. But there can 10-15 compulsory options and this code
if (!opt.a) {
console.log('a is required!');
return false;
}
if (!opt.b) {
console.log('b is required!');
return false;
}
if (!opt.c) {
console.log('c is required!');
return false;
}
can become lengthy and cumbersome. Is there any shorter or smarter way to write this? I was thinking of some common code.
If there are that many, you could put them in an array and check that way:
Note that I’ve gone for an
if (!(optname in opt))check there (rather thanif (!opt[optname])as you originally had), to allow for options that must be specified but for which0,false,undefined, or other falsey values are valid. Theincheck sees whether the option is there without worrying about its value being truthy.Slightly off-topic: You might choose to wait to fail until you’ve checked for all of the properties, as @Marcus points out in the comments. Also, you might consider throwing an exception rather than returning false, as someone failing to specify the options correctly should be an exceptional condition… But those are minor points.