2

I'm writing a JavaScript plugin that receives a set of settings, some required, some not. It's actually a plugin for Raphael.js but this question extends to jQuery plugins too.

My code looks something like the following:

jQuery.fn.myplugin = function (settings) { 
    settings = settings || {};
    var reqParam1= settings.requiredParameter1 || return; //Or throw? //Or ... ?

    /* More code */
}

If I determine that the plugin didn't receive all the required settings, what course of action should I take? The obvious and most conservative choice is to throw but what about in the case where the plugin functioning isn't 'essential'? By not 'essential' I mean purely an aesthetic enhancement or less-than-critical to the rest of the page. In this case could it be correct to die silently?

4

2 回答 2

2

throw如果出现致命问题,例如缺少强制参数,您可以这样做。决定这个插件的功能是否“必要”是调用者的责任。因此,您可以将插件调用包装在 try .. catch 块中,并将消息记录在 catch 块中。

try {
    $.myplugin( ... );
}
catch(e) {
    console.log('Feature not enabled');
}
于 2012-06-12T04:20:16.850 回答
1

如果这意味着您的插件无法运行(但尽量将强制参数保持在最低限度),您应该使用强制参数,并为其他所有内容使用默认值。

jQuery.fn.myplugin = function (settings) { 
    settings = $.extend({}, $.fn.myplugin.defaults, settings);
    if(!settings.requiredParameter1) throw "Missing requiredParameter1";

    /* More code */
}

jQuery.fn.myplugin.defaults = {
  optionalParameter1: true
}
于 2012-06-12T04:11:53.223 回答