JQuery silence prevention patterns

Is there any good practice to avoid your jQuery codes that don't work?

For example:

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

I know that every time this line is executed, the selector is designed to match at least one element or a certain number of elements. Is there any standard or good way to test this?

I thought of something like this:

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

I also think unit testing will be a valid option, not messing up the code.

My question may be silly, but I wonder if there is a better option than what I'm doing now or not. Also, maybe I'm wrong when checking if any element matches my selector. However, as the page continues to grow, selectors may stop matching some elements, and parts of the functionality may stop working unintentionally.

+6
javascript jquery
source share
3 answers

You can 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 () { }); 
+6
source share

This is not necessarily wrong when the selector matches nothing; it depends on your application. You can write your own validateNonEmpty plugin:

 jQuery.fn.validateNonEmpty = function() { if (this.length == 0) throw "Empty list detected - selector: " + this.selector; return this; // thanks @Matt }; 

Then you can do:

 $('something something').validateNonEmpty().doSomething(); 

Also note that you want to check if length 0 is equal to at least 0.

+6
source share

I would recommend using jQuery lint .

eg

 $(function(){ var foo = $('.this #is:my(complexSelector)'); }); 

will complain that you have an invalid selector (since this example selector is actually invalid, although I assume you know this :)), and that there are no elements that were actually found.

See http://js.azatoth.net/test/lint.html for an example.

+2
source share

All Articles