JQuery is a monad
importantshock.wordpress.com
importantshock.wordpress.com
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.
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.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.
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.
That being said, presenting monadic designs in this fashion could well help understand the basics, which is to be applauded.
Monads are abstract data types that satisfy three conditions: 1) They wrap themselves around other data types 2) They have an operation, confusingly called return, that actually performs the aforementioned wrapping 3) They have an operation called bind that allows to feed the value wrapped inside the monad into another function, as long as the function returns a monad. </quote>
What condition is not satisfied by decorators with method chaining?
A single counter-example (a monad in the above sense that can't be expressed as a decorator) would suffice.
If you squint at Haskell to the point that you start seeing methods in all monad uses, you're squinting so hard that the word "method" has lost all meaning and become a synonym for "function". That is to say, I can see how that argument goes, but it comes at the cost of totally devaluing the distinction between "method" and "function", something I'm not willing to do.
This is possible because jQuery defines it's contents inside each object numerically:
var jQueryObj = $(".someClass");
alert(jQueryObj[0].innerHTML);