In development mode, sometimes we make stupid mistakes like
misspelling a selector. Many people have been caught by passing a
"complex" selector to .is() and expecting it to work.

There is little debugging or error-checking done in jQuery to alert
you of potential problems.

I had a thought after discussing this with someone recently - would a
"debug" plugin be useful to detect common mistakes and warn the
developer? Not all the info would necessarily be errors or problems,
but if you are not seeing things work as expected it might be a way to
find the problem more quickly.

I wrote a quick proof-of-concept to illustrate how it might work.
http://www.javascripttoolbox.com/jquery/jquery.debug.html
The code is also pasted below.

The logging/alerting mechanism is obviously crude, but it's just a
poc.

Ideally I would like to see a heavily-commented jQuery source that
includes error-checking and warnings built-in as a "developer"
package. But assuming that won't happen, this is a way to "patch in"
this kind of functionality.

Any thoughts?

Matt Kruse

SOURCE:

<html>
<head>
        <title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-
latest.pack.js"></script>
<script type="text/javascript">
(function($) {
        $.fn._init = $.fn.init;
        $.fn.init = function(selector, context) {
                var result = $.fn._init(selector,context);
                if (typeof selector=="string" && result.length==0) {
                        $.fn.debugWarn("selector ["+selector+"]
returned 0 matches");
                }
                return result;
        }

        $.fn._fadeOut = $.fn.fadeOut;
        $.fn.fadeOut = function(speed,callback) {
                if (typeof speed!="number" && typeof
$.fx.speeds[speed]=="undefined") {
                        $.fn.debugWarn("speed ["+speed+"] is not a
valid jQuery speed constant");
                }
                return $.fn._fadeOut(speed,callback);
        }

        $.fn._is = $.fn.is;
        $.fn.is = function(selector) {
                // This test would obviously need to be improved
                if (typeof selector=="string" && /[\s
\>]/.test(selector)) {
                        $.fn.debugError("selector ["+selector+"] is
too complex to pass to .is()");
                }
                return $.fn._is(selector);
        }

        $.fn.debugWarn = function(str) {
                if (window.console) { window.console.warn("jQuery:
"+str); }
                else { alert("jQuery WARNING: "+str); }
        }
        $.fn.debugError = function(str) {
                if (window.console) { window.console.error("jQuery:
"+str); }
                else { alert("jQuery ERROR: "+str); }
        }

})(jQuery);

$(function() {
        $('div.x').fadeOut("really slow");
        $('test');
        $('div.y').is("body > div");
});

</script>
</head>
<body>

<div class="x">Test DIV</div>
<div class="y">Test DIV 2</div>

</body>

</html>

Reply via email to