3 ms·
Great strength, but also a great weakness of jQuery. My most common jQuery bug is a rule that doesn't get applied correctly (wrong selector) and it just fails q
by jpcx01 18y ago
Great strength, but also a great weakness of jQuery. My most common jQuery bug is a rule that doesn't get applied correctly (wrong selector) and it just fails quietly. It's very hard to write console.log statements, or even do debugging breakpoints on a long method chain.
Probably a way to solve this problem. Maybe jQuery needs a monadic method that logs the current chain object without interupting the flow.
$("div.blah > h1").logCurrent("Showing current item:")
where log current would display your message along with a representation of the current state of the transitionary object, and then return it back so you can continue on with the chain.
Something like this probably already exists. Or it wouldnt be too hard to write a plugin.
- shutter 18y agoSomething like this would work: jQuery.fn.logCurrent = function (title) { console.log(title, $.makeArray(this).join(', ')); return $(this); }; But it depends what you want to log for each element. I think Firebug's output would give clickable links in that case, but you could alternatively cherrypick class names or the like.
- simonw 18y agoYou can also add assertions to jQuery about the length of the chain: jQuery.fn.assertLength = function(i) { if (this.length != i) { throw "Expected " + i + " matching elements, selection was: " + this.get(); } return this; } If you're using jQuery 1.3 (with its new selector property), a better implementation might be: jQuery.fn.assertLength = function(i) { if (this.length != i) { throw "Expected " + i + " matching elements, got " + this.length + ", selector was: " + this.selector; } return this; } You can then introduce the assertLength method in to your chains like so: $('div#intro a').assertLength(3).click(...) If the number of matched elements doesn't match the expected, you get a descriptive exception raised which stops execution and shows up in the error console.
- iamwil 18y agoI remember Raganwald talking about something similar. http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html http://weblog.raganwald.com/2008/01/objectandand-objectme-in... Scroll down and he talks about #tap in Ruby 1.9, which he uses to insert a "tap" into a long method chain to figure out what's going on there, instead of having to break the chain and store the results in a variable in order to inspect it.