In all honesty, this was a functionality I was hot for maybe a year
ago, but probably wouldn't need much today. I cache collections all
the time, and I recommend it highly to new users. Users of jQuery
should be WAY more aware of the simple fact that $() is a constructor,
but many are not. If there's anything we could do as a community, it
would be to further encourage the practise.
That said, I think the idea that multi-line chains should be frowned
upon is a bit short-sighted. Take this piece of code:
$('tr.parent')
.css("cursor","pointer")
.attr("title","Click to expand/collapse")
.click(function(){
$(this).siblings('.child-'+this.id).toggle();
});
It completely breaks your Best Practise of never chaining across
multiple lines, but I don't think there's anyone on this list who
would decry that example as unreadable or "cryptic."
I think a lot of people, including myself, use a jQuery chain as an
opportunity to briefly interact with the DOM after doing setting up an
instance. This isn't the world's greatest example, but I think it
demonstrates why this might be desirable.
var foo = {
$el:$("#bar"),
emotion: Math.rand < .5 ? "sad" : "happy",
init:function() {
var self = this;
this.$el.click(function() { alert(foo.emotion);
})
.iff(this.readyToDoSomeWork)
.load("url.php",function(data) {
self.update(data);
})
.end()
.addClass(this.emotion);
},
readyToDoSomeWork:function() {
return this.emotion == "happy";
},
update:function(data) {
this.$el.html(data);
},
};
foo.init();
It is easy to code around a chainable conditional using cached
collections, but, like with the suggestion I had for .index(), the
idea here is to save developers the stops and starts and extra
variables that might not be necessary. As I said before, I'm not even
sure I myself would use this, my point is just that there is
considerable demand for the functionality, and even when you *do*
cache your selections, it doesn't completely prevent you from needing
to break chains.
Ultimately this discussion boils down to taste. How jQueryish should
jQuery be? How Javascripty? To answer the question, "how is this
better?" I would say, however, that when you have to refer to the same
element three times in six lines of code just to execute any piece of
conditional logic, you're just giving up the power of chaining
altogether just in favor of more "Javascriptiness." Which is, of
course, better than "PHPness," at least when you say it out loud :p
--adam