What is considered the best way to handle misuse in a jQuery plugin — ignore, or throw an error? In the situation I’m working with, I have a plugin that binds some functionality to an image. Once bound, you can do some other things through methods, e.g. set or get state information which can be changed by client interaction, e.g.:
$('selector').myPlugin();
$('selector').myPlugin('some-method',data);
What should one do when:
- a selector contains no relevant elements (suspect the answer to this is, nothing, no error)
- a method, which is only relevant to a previously bound element, is applied to a selector with no relevant elements
- a method contains parameter data that is invalid
I feel like the right thing to do in some cases i just to ignore anything that’s invalid or doesn’t apply and proceed without errors. A big part of the “jQuery way” is to act in a predictable fashion as much as possible, which to me means, don’t break unless you have to.
On the other hand, this makes debugging more difficult, since you won’t ever get any errors when doing things you aren’t supposed to. Sometimes that could be reasonable (e.g., applying a plugin to a set of elements for which only a subset is relevant). On the other hand, doing things like trying to apply a specific method to an irrelevant element, or passing bad parameter data, could cause more trouble in the long run to ignore errors.
Is there any conventional wisdom on this? Add an “ignore-errors” option?
On bullet 1 if you are following the patterns on this page http://docs.jquery.com/Plugins/Authoring, you are doing the right thing. Namely this:
On bullet 3 ignore parameter names that you don’t use. Throw an exception when they use bad data in one of your parameters. This will I believe stop all processing of matched items in the selector. You could also provide a debug mode where it will throw the exception. This way they can turn it on during testing and leave it off when they go into production.
On bullet 2 I’m tempted to say go with what you picked out of what I said for bullet 3. If it is something like getting data associated with an element that hasn’t had a setXXXX called, just return an empty set of data.