Essential JavaScript Design Patterns For Beginners
addyosmani.com
addyosmani.com
As other patterns covered display aspects of DRY-ness with JavaScript, let's take a look at how to write DRY code using jQuery. Note that where jQuery is used, you can easily substitute selections using vanilla JavaScript because jQuery is just JavaScript at an abstracted level.
That is jibberish, and it shows in the code examples: Using an ES5 shim is best-practice these days, so that you can use Array.prototype.forEach and not jQuery.each (with its weird argument order), amongst other things that are commonplace in modern JavaScript code. Yet the auther defers to jQuery throughout.
As jQuery is accepted as one of the best options for DOM-manipulation and selection, we'll be using it for our DOM-related examples.
More likely that the document is filled with jQuery because the author is heavily involved with the jQuery project, no?
Says who?
I'm guessing about 90% of the reason most people start using a library like jQuery is because it lets you find almost any DOM element in a single step with a familiar syntax. And about 9% of the rest is probably to make AJAX less painful. Does your unspecified ES5 shim provide these features?
If not, a lot of people are going to be using a library like jQuery anyway, and you're advocating using an extra (unspecified) library to get portable utility functions that also work in older browsers. What happened to DRY? ;-)
This isn't to say that polyfilling doesn't have its place or isn't useful. I just challenge your claim about what is best practice, because I think the argument is far from compelling in the common case that a developer is already using another library with similar utility functions (which many, many general purpose JS libraries have, because the language itself was so slow to provide them; it's like strings in C++ all over again).
For one thing, these APIs only support selectors as expressive as the browser they're running in, which could be a significant disadvantage for IE8 in particular.
For another thing, querySelectorAll() doesn't actually return the array one might expect, but rather a NodeList. That means that doing obvious things like iterating over all the elements you find with forEach() is, well, not so obvious at all.
So I think I stand by my previous position: a lot of people are going to have good reasons to use another library anyway, in which case they might also have access to various convenience functions, in which case relying on ES5 for the same functionality and therefore relying on an ES5 shim to support older browsers is unnecessary.
jQuery is the de-facto DOM library (whether it should be or not), failure to see this is ignorance.
I'm not sure how much you really need to test an each() loop. It is a very simple thing as are most of the other features introduced in ES5 that can be shimmed. jQuery doesn't include many of these new features, and I disagree with you that you should just omit them from your code because your DOM library, of all things, doesn't include them.
All the ES5 shims do is implement these functions exactly to the standard, and doing so is a very simple thing. Further, the code in a shim is only run in old versions of IE: New IE, and pretty much all running versions of non-IE browsers, implement these functions in native code (which obviously is much faster). jQuery does not defer to Array.prototype.forEach if it is available.
jQuery is the de-facto DOM library
No, it really isn't. There's a huge distance to travel from being the most popular to being "de-facto."
Hmmm, seems like a huge distance to travel from being 'I think ES5 shims are awesome' to a 'best-practice' these days. I'd be hesitant to use the kriskowal library in production, especially since it states 'This package requires quite a bit more attention and testing. It is not likely to behave as advertised in a large cross-section of browsers.'
Its demographic, or target audience, is irrelevant, because it is everywhere, and much to the detriment of 'pure javascript' (some might argue).
It'll remain that way until differing browser implementations converge and obviate the need for an abstraction that papers over the cracks.
Could you expand on this a little bit, particularly the "other things that are commonplace in modern JavaScript code"? As someone who's just getting into heavy client-side JS, it still feels like the whole world is very jQuery-centric. In particular, material targeted at beginners (such as this article) tends to lean heavily on jQuery for anything more complex than really basic core language stuff. I'd be very interested in alternatives, if only to broaden my horizons.
Regarding your other question, jQuery/JavaScript is a false dichotomy. jQuery's just another DOM library with a few utility functions.
https://github.com/kriskowal/es5-shim
Especially when you note that JavaScript is not just run in browsers these days, and that most server-side deployments do implement ES5 features, it makes very little sense for modern tutorials to avoid ES5 features unless they are trying to demonstrate drop-in snippets with no library dependencies. It seems clear that the author is not shy about including other libraries with his code.
> This package requires quite a bit more attention and testing.
> It is not likely to behave as advertised in a large cross-section of browsers.
That doesn't sound like a cross-browser solution. In fact, it doesn't sound like a professional-level solution at all.
Perhaps one day it will be, but if you're arguing that using this kind of library is a best practice today and that developers should eschew jQuery in favour of such alternatives, then I don't think your position is credible at all.
Considering you don't even get the opportunity to detect the problem and turn off the failing progressive enhancement in favor of the non-js behavior, this doesn't seem like a realistic alternative to just writing pre-ES5 code that's known to work.
If you are interested in alternatives to jQuery there are many of them available. I am personaly a big fan of the Dojo toolkit, since it is kind of batteries-included, it does less magic $ stuff and it supports a decent module system.
I defer to him who made a plea, for consultants' reports to become poetry: https://www.youtube.com/watch?v=GUSLEJB9_LU
Perhaps, as _why's Poignant Guide, the poet goes too far: and then we lose too much substance. But 150 pages? Au revoir: there must be a cleaner, deeper essence. For I delight in the everyday code, which is fun, dramatic, sweeping, and wry, and manufactured examples of jQuery's road are nowhere as cool as an eval/apply.
The worst part is, he knows not what he does. For I opened him up to a random page, and saw what he said -- and I don't mean to fuss, but I can't help but feeling a little rage:
The Iterator Pattern is a design pattern where iterators (objects that allow us to traverse through all the elements of a collection) access the elements of an aggregate object sequentially without needing to expose its underlying form.
Iterators encapsulate the internal structure of how that particular iteration occurs - in the case of jQuery's $(el).each() iterator, you are actually able to use the underlying code behind $.each() to iterate through a collection, without needing to see or understand the code working behind the scenes that's providing this capability. This is a pattern similar to the facade, except it deals explicitly with iteration.
No, my good sir, ten times no. The iterator pattern as was discussed (in Design Patterns, and such and so), has nothing to do with that construct. Iterators speak polymorphism out loud, freeing us from finities and the rest of the crowd. Let me illustrate with a simple collection of rational numbers -- in Cantor's bijection:
function gcd(lo, hi) {
return lo > hi ? gcd(hi, lo) : lo === 0 ? hi : gcd(hi % lo, lo);
}
function rational_iterator() {
var num = 0, denom = 1;
return {
hasNext: function () {
return true;
},
next: function recurse() {
var rat = [num, denom];
if (denom === 1) {
denom = num + 1;
num = 1;
} else {
denom -= 1;
num += 1;
}
return gcd(rat[0], rat[1]) === 1 ? rat : recurse();
}
};
}
And perhaps arrays are not quite your style, so you might like me to convert them to strings. That requires a new map method -- I'm not in denial -- but that's pretty simple in the grand scheme of things: function map(seq, fn) {
var i = 0;
return {
hasNext: function () {
return seq.hasNext();
},
next: function () {
return fn(seq.next(), i++);
}
};
}
var rationals_as_strings = map(rational_iterator(), function (x) { return x.join("/"); });
Our lazy maps and infinite sequence save us from any pro-jQuery pretense and instead show us a taste of that vision of knowing your code, with modest concision.That is not entirely true, internal iterators in the style of Smalltalk and Ruby have all the capabilities of GOF-style external iterators, and jQuery (or underscore's) each is a restricted kind of internal iterator.
And while that is (sadly) not supported at the moment these could very well delegate to an arbitrary implementor of Javascript's own internal iterator protocols (JS 1.6's "Array extras"), leading exactly to the capabilities you describe (including but not limited to polymorphism).
Furthermore, external iterators are of little use, value and class when you have blocks, or at least "full" anonymous functions. It's unsurprising to have them in the C++ and Java-based GOF, but they don't belong anywhere near JavaScript.
[http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp...]
I like the references to Backbone.js and other modern frameworks...the explanation of Backbone's router vs Spine's controller was particularly helpful, mostly because I know Backbone's router is not a controller but hadn't taken the time to see how Spine does it.
I thought the introduction...everything before the actual examples/cases, was a little too long-winded for me. It was interesting to read as an experienced programmer, but I can't imagine a beginner trudging through all of that without seeing a simplified use case to break up the long narrative text. If the audience for this book is beginners, why go into such great detail about the philosophy of patterns (including a discussion of antipatterns) when most beginners are at the level where they probably don't know much OOP or even things like closures?
Otherwise, another fantastic addition to the open-source bookshelf.
http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-loo...
`this` in JS generally incurs a lot of wrath, but this is one cool hack with `this`.
Because, you know, the pattern is not the solution, but the sum of problem + context + solution.
I had the sudden realization that using and recognizing design patterns was exactly what I was missing to get over the beginner-intermediate hump in the learning curve. I'd heard of design patterns before, but they'd come across as a rather lofty concept.
After a second and third look, I realized its immediately practical boilerplate stuff that one can copy/paste (and even more importantly, recognize in 3rd-party plugins and frameworks). Design patterns should follow after reading a 'cookbook'. Its just a name for techniques beyond your basic for/while loops (which could be thought of as the simplest of design patterns).
Pub/Sub can be viewed as a simple form of the observer pattern, and MVC is a more elaborate form (notice that in the article's TOC, MVC comes right after Observer). I've lost a lot of time banging my head on MVC too soon. For some reason, the introductory articles on MVC I was finding made scant mention of design patterns. Great to see more material discussing the concepts together lately.
As for the article: it's a valuable resource. Especially for those that believe jQuery is JavaScript. It's a goodie.