Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns for avoiding jQuery silent fails

Is there any good practice to avoid your jQuery code silently fail?

For example:

$('.this #is:my(complexSelector)').doSomething();

I know that every time this line get executed, the selector is intended to match at least one element, or certain amount of elements. Is there any standard or good way to validate that?

I thought about something like this:

var $matchedElements = $('.this #is:my(complexSelector)');
if ($matchedElements.length < 1)
    throw 'No matched elements';
$matchedElements.doSomething();

Also I think unit testing would be a valid option instead of messing the code.

My question may be silly, but I wonder whether there is a better option than the things that I'm currently doing or not. Also, maybe I'm in the wrong way checking if any element match my selector. However, as the page continues growing, the selectors could stop matching some elements and pieces of functionality could stop working inadvertently.

like image 477
mati Avatar asked Jun 15 '10 18:06

mati


1 Answers

You could write a plugin:

jQuery.fn.requireElements = function (amount, exactMatch) {
    if (amount === undefined) {
        amount = 1;
    };

    if (this.length < amount || this.length > amount && exactMatch) {
        throw new Error(this.length " elements instead of " (exactMatch ? "at least " : "") + amount);
    };

    return this;
};

Then:

$('yourSelector').requireElements(2).bind('click', function () {

});
like image 133
Matt Avatar answered Oct 04 '22 07:10

Matt