epub-gen
Version:
A library to generate EPUB from HTML
25 lines (22 loc) • 142 kB
JavaScript
// Generated by CoffeeScript 2.3.2
(function() {
var EPub, optionsAlice, optionsHtmlPaste, path;
EPub = require("./lib");
path = require("path");
optionsHtmlPaste = {
title: "Simple Test Book",
author: "Cyril Hou",
publisher: "txt.sx",
cover: "https://dn-baiim.qbox.me/54bb3eb8fdadac375c311be9.jpg", // url or path
version: 3,
content: [
{
title: "What's the Dam Problem",
author: "Heather Hansman",
excludeFromToc: true,
data: "<div class=\"postField postField--body\" data-scroll=\"native\"><section name=\"b972\" class=\" section--last\"><div class=\"section-divider layoutSingleColumn\"><hr class=\"section-divider\"></div><div class=\"section-content\"><div class=\"section-inner layoutSingleColumn\"><p name=\"1273\" id=\"a1273\" class=\"graf--p graf--first\">The salmon look stressed. Behind the algae-streaked windows at Seattle’s Hiram Chittenden fish ladder they’re bumping heads, flipping in the current, and pointing their narrow jaws upstream.</p><p name=\"f31a\" id=\"f31a\" class=\"graf--p\">To get to this point, they’ve already swum through the Straits of Juan de Fuca and the Puget Sound, and jumped through the first 17 steps of the ladder, which looks like a skinny set of concrete bleachers. Most fish passes aren’t as visible at the Seattle one, which has an observation deck where you can peer into the steps, but the way the fish have to work around a manmade barrier in the river is common. From here, the fish will keep following the current upstream to spawn in the stream where they were born. Anadramous fish are imprinted, Twilight style, in the rivers where they hatched, so depending on where they came from, they’ll still have several more dams to navigate.</p><p name=\"0111\" id=\"a0111\" class=\"graf--p\">There are more than 80,000 dams in the U.S. and nearly all of them have some kind of fish pass. They range from multi-step ladders like the Seattle one to elevators that suck the fish upstream to nature-like diversion canals. Some of them have been in place since the colonists started farming, and in 1890 the state of Washington passed a law that all dams, “wherever food fish are wont to ascend,” needed to include a fishway. The rest of the country eventually followed suit. Now, any new hydropower dam needs to get its fish ladder design cleared by the Federal Energy Regulatory Commission. But there aren’t a ton of new dams going in, and it’s becoming increasingly clear that just because a ladder exists it doesn’t mean that fish are going to figure out how to use it, or want to.</p></div><div class=\"section-inner sectionLayout--outsetColumn\"><figure name=\"e046\" id=\"e046\" class=\"graf--figure postField--outsetCenterImage\"><div class=\"aspectRatioPlaceholder is-locked\" style=\"max-width: 1020px; max-height: 765px;\"><div class=\"aspect-ratio-fill\"></div><img class=\"graf-image\" data-image-id=\"a1*-zwVwLnT7QJQ9HDrvOZCyw.jpeg\" data-width=\"3264\" data-height=\"2448\" data-action=\"zoom\" data-action-value=\"1*-zwVwLnT7QJQ9HDrvOZCyw.jpeg\" src=\"https://dn-baiim.qbox.me/54bb3ee5fdadac375c311c25.jpg\"></div><figcaption class=\"imageCaption\">Spillway of Seattle’s Hiram Chittenden locks. Flickr/<a target=\"_blank\" href=\"https://www.flickr.com/photos/acordova/7039116327/in/photolist-bJ2j3B-eQZK1c-7uR7Q4-H9FWR-oHsUa2-fQ4p9n-p3W1Ss-6QhD9F-abgFSw-55L3pG-nnsZoy-9uvG1f-bv7xqj-daY3HN-bJ2jAR-bJ2jVK-73CqVE-pkeAPx-91grS2-dgg8w4-bv7wfA-bv7x2s-bJ2jaK-bv7wvN-bv7woo-bv7wDQ-bJ2jpg-bJ2ikM-bv7w19-bJ2hEp-dgNvCs-bJ2jMT-iEN3Vt-9uvFM7-6RDxoz-kmzYce-8KZrPr-8KZAog-e848hd-8bpi3y-8bpi7d-d5wCXS-dcmWzN-f5k8FN-dgNtiR-aarCDC-dgNt5j-hTaCFu-91gspc-fkfv3d\" data-href=\"https://www.flickr.com/photos/acordova/7039116327/in/photolist-bJ2j3B-eQZK1c-7uR7Q4-H9FWR-oHsUa2-fQ4p9n-p3W1Ss-6QhD9F-abgFSw-55L3pG-nnsZoy-9uvG1f-bv7xqj-daY3HN-bJ2jAR-bJ2jVK-73CqVE-pkeAPx-91grS2-dgg8w4-bv7wfA-bv7x2s-bJ2jaK-bv7wvN-bv7woo-bv7wDQ-bJ2jpg-bJ2ikM-bv7w19-bJ2hEp-dgNvCs-bJ2jMT-iEN3Vt-9uvFM7-6RDxoz-kmzYce-8KZrPr-8KZAog-e848hd-8bpi3y-8bpi7d-d5wCXS-dcmWzN-f5k8FN-dgNtiR-aarCDC-dgNt5j-hTaCFu-91gspc-fkfv3d\" class=\"markup--anchor markup--figure-anchor\" rel=\"nofollow\">acordova</a></figcaption></figure></div><div class=\"section-inner layoutSingleColumn\"><p name=\"3aea\" id=\"a3aea\" class=\"graf--p graf--startsWithDoubleQuote\">“We found that, in general, engineered fish ladders have not performed up to everyone’s expectation,” says John Waldman, author of<em class=\"markup--em markup--p-em\">Running Silver: Restoring Atlantic Rivers and Their Great Fish Migrations</em> and a recent study about how migratory fish navigate dams. The numbers from the study were grim. Less than three percent of American shad, for instance, were making it back upstream to their spawning grounds.</p><p name=\"e451\" id=\"e451\" class=\"graf--p\">All fish migrate to a degree, but dams have the biggest disrupting force on anadramous fish, like salmon or shad, which spawn in rivers but spend most of their lives in the ocean, and catadramous ones, like eel, which live in freshwater, but swim out into the ocean to do it.</p><p name=\"b0f8\" id=\"b0f8\" class=\"graf--p\">There are other factors, like overfishing and climate change, which also hurt declining fish populations, but dams are the most obvious, and because of that, environmental engineers, dam operators, and fish biologists have been trying, with limited success, to design ways for fish to get past them.</p><p name=\"e1a5\" id=\"e1a5\" class=\"graf--p\">In the middle of last century, dams were seen as the answer to a wide range of issues, from water supply to energy security. JFK boosted dam building in his campaign speeches. From the 1920s to the ‘70s, the Army Corps of Engineers built tens of thousands of dams, ones like the Columbia River’s Grand Coulee, which has cut off more access to fish habitat than any other structure in the world. That boom in dam building took a toll. “Many fishways were originally designed for adult salmon over 50 years ago, but we’ve recently found that they don’t work well for other species,” says USGS fish biologist Alexander Haro.</p><p name=\"3a71\" id=\"a3a71\" class=\"graf--p\">He’s trying to find ways to make them more appealing. At the Conte Anadramous Fish Branch, in Massachusetts, Haro sends fish through a respirometer to see how much energy they exert when they’re stressed, and through what he calls a “sprint swimming flume,” to see how fast they can swim and for how long. “It’s kind of like a high-speed treadmill for fish,” he says. He’ll use that data to try to design fishways that actually work.</p><p name=\"2837\" id=\"a2837\" class=\"graf--p\">The biggest issue, according to Jim Taurek, a NOAA restoration ecologist, is that different fish swim very differently. Some, like salmon, can jump high and sprint, while others — sturgeon for instance — mosey upstream. Alewife freak out in confined spaces and shad don’t like air bubbles.</p><p name=\"4570\" id=\"a4570\" class=\"graf--p\">Because of that, there are almost as many ways to design a passage as there are fish trying to swim through it. “In general, the lower the slope of a fishway, the easier fish can ascend, but that also means the fishway needs to be longer, and many fish will not stay in a fishway structure for very long,” Haro says. It’s possible to have a theoretically perfectly designed ladder that keeps fish stranded on the bottom, because they don’t like its style.</p></div><div class=\"section-inner sectionLayout--outsetColumn\"><figure name=\"72dc\" id=\"a72dc\" class=\"graf--figure postField--outsetCenterImage\"><div class=\"aspectRatioPlaceholder is-locked\" style=\"max-width: 1020px; max-height: 680px;\"><div class=\"aspect-ratio-fill\"></div><img class=\"graf-image\" data-image-id=\"a1*Gp4-XDgUw0jvKEgK9LInKw.jpeg\" data-width=\"1200\" data-height=\"800\" data-action=\"zoom\" data-action-value=\"1*Gp4-XDgUw0jvKEgK9LInKw.jpeg\" src=\"https://dn-baiim.qbox.me/54bb3eadfdadac375c311bda.jpg\"></div><figcaption class=\"imageCaption\">French Lake Dam fish ladder, Wichita Mountains Wildlife Refuge, Oklahoma. Flickr/<a target=\"_blank\" href=\"https://www.flickr.com/photos/lsmith2010/14442265487/in/photolist-o1donn-f4Di9G-ojrTS6-8ut2AT-55wRSV-5PjiW9-hZcSXc-p1eZ8a-7pSen7-71rTyU-56DJpD-hc7bxS-5X4yX5-o3o9yk-agacdQ-5EvKrm-f7RMX-dWuZyS-fs1R9h-ewH3Fv-4EmseE-4EmsLo-q1mBer-jTkFt-61Kwuc-5oUEak-ebk2hy-4RrwTc-nUajVq-8KZrPr-jSVn1-7DfSn1-47v92-9PQvJ1-h7ahu-a5cRZb-9Q3Cgf-sSP9-9Aftud-6tB18W-fmxw91-9eZs2J-pip3HJ-55VKBQ-awBq5i-iMYJ4-47viD-cHhNa5-mDiCJP-o59ARA\" data-href=\"https://www.flickr.com/photos/lsmith2010/14442265487/in/photolist-o1donn-f4Di9G-ojrTS6-8ut2AT-55wRSV-5PjiW9-hZcSXc-p1eZ8a-7pSen7-71rTyU-56DJpD-hc7bxS-5X4yX5-o3o9yk-agacdQ-5EvKrm-f7RMX-dWuZyS-fs1R9h-ewH3Fv-4EmseE-4EmsLo-q1mBer-jTkFt-61Kwuc-5oUEak-ebk2hy-4RrwTc-nUajVq-8KZrPr-jSVn1-7DfSn1-47v92-9PQvJ1-h7ahu-a5cRZb-9Q3Cgf-sSP9-9Aftud-6tB18W-fmxw91-9eZs2J-pip3HJ-55VKBQ-awBq5i-iMYJ4-47viD-cHhNa5-mDiCJP-o59ARA\" class=\"markup--anchor markup--figure-anchor\" rel=\"nofollow\">lsmith2010</a></figcaption></figure></div><div class=\"section-inner layoutSingleColumn\"><p name=\"0509\" id=\"a0509\" class=\"graf--p\">In addition to figuring out the size and shape of the structure you also need to design an appealing entrance, and to make sure the river flow points the fish in the right direction. Salmon can’t use an elevator if they can’t find the door. “Building fish ladders, even thought it’s engineering, it’s also art,” Waldman says.</p><p name=\"803d\" id=\"a803d\" class=\"graf--p\">Then you have to engineer the other side, for downstream fish migration. That’s simpler from a design perspective — the hardest part is teasing the fish out of the main current and into the fish pass — but it can be complicated from the financial side. Running water around the dam is the simplest solution, but utilities make their money on river flows, so they’re hesitant to spill a single drop.</p><p name=\"8274\" id=\"a8274\" class=\"graf--p\">Because of that the workarounds are myriad. Taurek says they’ve tried to truck juvenile fish to less-dammed rivers before they start migrating. That way, when they want to spawn, they come back to the new river. He says it works pretty well, but it’s not cheap and it doesn’t really address the heart of the issue.</p><figure name=\"bf6d\" id=\"bf6d\" class=\"graf--figure postField--outsetLeftImage\"><div class=\"aspectRatioPlaceholder is-locked\" style=\"max-width: 525px; max-height: 700px;\"><div class=\"aspect-ratio-fill\"></div><img class=\"graf-image\" data-image-id=\"a1*lvHBjnavz12mkcqq7lhnpQ.jpeg\" data-width=\"1200\" data-height=\"1600\" data-action=\"zoom\" data-action-value=\"1*lvHBjnavz12mkcqq7lhnpQ.jpeg\" src=\"https://dn-baiim.qbox.me/54bb3e83fdadac375c311bab.jpg\"></div><figcaption class=\"imageCaption\">The salmon ladder at the Bonneville Dam on the Columbia River in Oregon. Flickr/<a target=\"_blank\" href=\"https://www.flickr.com/photos/snowmail/12800308103\" data-href=\"https://www.flickr.com/photos/snowmail/12800308103\" class=\"markup--anchor markup--figure-anchor\" rel=\"nofollow\">snowmail</a></figcaption></figure><p name=\"6ef4\" id=\"a6ef4\" class=\"graf--p\">Other creative alternatives tend to be expensive, resource intensive (it’s not uncommon for the Department of National Resources to fly fish around dams by helicopter), or slightly crazy. One alternative, Washington-based Whooshh Innovations’ Salmon Cannon (yes, it is exactly what it sounds like), got spoofed on<a target=\"_blank\" href=\"https://www.youtube.com/watch?v=l9qA8c-E_oA\" data-href=\"https://www.youtube.com/watch?v=l9qA8c-E_oA\" class=\"markup--anchor markup--p-anchor\" rel=\"nofollow\">John Oliver’s Last Week Tonight</a>. “Clearly this is the best object that’s ever been invented,” Oliver said, as he launched fish into Jon Stewart’s studio. It seems ridiculous, but the Washington Department of Fish & Wildlife bought one, and started testing it with hatchery fish on the Washougal River in September. Whooshh says it’s less stressful on the fish, and can be used to get them over any height dam, but its actual usability is still unproven.</p><p name=\"3cb3\" id=\"a3cb3\" class=\"graf--p\">As the ageing U.S. dams start to break down, and more empirical evidence shows that fish populations are being depleted, there’s been a growing movement to eliminate dams all together. The non-profit advocacy group American Rivers has a whole department dedicated to dam removal. Last year, a documentary,<a target=\"_blank\" href=\"https://vimeo.com/ondemand/damnation/89928979\" data-href=\"https://vimeo.com/ondemand/damnation/89928979\" class=\"markup--anchor markup--p-anchor\" rel=\"nofollow\">DamNation</a>, won the Audience Choice award at South by Southwest and galvanized environmentalists and river lovers to take down dams, sometimes with Ed Abbey-style monkeywrenching strategies.</p><p name=\"d57b\" id=\"d57b\" class=\"graf--p\">There’s weight behind their goals, if not always their techniques. When you get rid of a dam, fish come back, often in exponential numbers and at awesome speeds. When the Edwards Dam on Maine’s Sebasticook River came down in 1999, the alewife population went from zero to three million in 10 years. In 2011, the National Park Service<a target=\"_blank\" href=\"https://www.youtube.com/watch?v=4LxMHmw3Z-U\" data-href=\"https://www.youtube.com/watch?v=4LxMHmw3Z-U\" class=\"markup--anchor markup--p-anchor\" rel=\"nofollow\">blew up two dams</a> on the Elwha River in Olympic National Park. It was the largest dam removal in history, and now, three years later, Chinook salmon are spawning in upstream habitats for the first time in 100 years.</p></div><div class=\"section-inner sectionLayout--outsetColumn\"><figure name=\"0870\" id=\"a0870\" class=\"graf--figure postField--outsetCenterImage\"><div class=\"aspectRatioPlaceholder is-locked\" style=\"max-width: 1020px; max-height: 681px;\"><div class=\"aspect-ratio-fill\"></div><img class=\"graf-image\" data-image-id=\"a1*GIU0UrBeoHKRVZLLNygQ8Q.jpeg\" data-width=\"1200\" data-height=\"801\" data-action=\"zoom\" data-action-value=\"1*GIU0UrBeoHKRVZLLNygQ8Q.jpeg\" src=\"https://dn-baiim.qbox.me/54bb4a3ea44ad6bf2b3a06bd.jpg\"></div><figcaption class=\"imageCaption\">The Elwha dam before it was removed.</figcaption></figure></div><div class=\"section-inner layoutSingleColumn\"><p name=\"637f\" id=\"a637f\" class=\"graf--p\">But it’s not that straightforward, which is why scientists are still trying to design the perfect fish passage. “A lot of people talk a good story, like, ‘Let’s just take that dam out,’” Taurek says. “That’s our preference, but in a lot of cases because of the social challenges, you’ve got to have alternatives.” Aside from power generation — about seven percent of U.S. power comes from hydro and in Washington State it’s as high as 75 percent — many dams are now embedded into the cultural and physical geography around them. We use reservoirs for drinking water, and, especially in old mill towns in the Northeast, the town infrastructure has built up around the dam. Plus, it’s expensive to knock out a dam and rebuild an ecosystem. The Elwha project cost $26.9 million.</p><p name=\"ce81\" id=\"ce81\" class=\"graf--p\">So what’s the solution? Given the options, blasting fish over dams in air cannons doesn’t sound quite as outlandish as you might think. Waldman and Taurek advocate for nature-like fishways, meandering streams that go around dams and mimic the native ecosystem. They say they’re the best alternative for fish viability, but, because they need to be low angle, and require a lot of land, they don’t make sense in many situations, especially on high head hydro dams in the West. “I’m not totally anti fish ladder,” Waldman says, “there are some small rivers and streams where fish ladders work great for river herring, but I think all dams should have an existential crisis, to see if they’re really necessary.”</p><p name=\"5bd1\" id=\"a5bd1\" class=\"graf--p graf--last\">But for now, the only things having existential crises are probably the fish, who are working their way back to where they’re from, thrown off by weirs and ladders. It’s not clear if fish even have feelings, but as the Seattle salmon thrash against the glass, it’s easy to imagine them questioning what kind of madness brought them to this point.</p></div></div></section></div>"
},
{
author: ["PhotoEl"],
beforeToc: true,
data: "<h1>Learning JavaScript Design Patterns</h1>\n<a href=\"filenametest.xhtml\">Test custom file link</a>\n<div lang=\"en\"><div id=\"RIL_IMG_1\" class=\"RIL_IMG loaded\"><img src=\"https://dn-baiim.qbox.me/54bb3e8dfdadac375c311bb8.jpg\"><caption><cite></cite></caption></div><p nodeindex=\"14\">Design patterns are reusable solutions to commonly occurring problems in software design. They are both exciting and a fascinating topic to explore in any programming language.</p><p nodeindex=\"15\">One reason for this is that they help us build upon the combined experience of many developers that came before us and ensure we structure our code in an optimized way, meeting the needs of problems we're attempting to solve.</p><p nodeindex=\"16\">Design patterns also provide us a common vocabulary to describe solutions. This can be significantly simpler than describing syntax and semantics when we're attempting to convey a way of structuring a solution in code form to others.</p><p nodeindex=\"17\">In this book we will explore applying both classical and modern design patterns to the JavaScript programming language.</p><h2 nodeindex=\"18\">Target Audience</h2><p nodeindex=\"19\">This book is targeted at professional developers wishing to improve their knowledge of design patterns and how they can be applied to the JavaScript programming language.</p><p nodeindex=\"20\">Some of the concepts covered (closures, prototypal inheritance) will assume a level of basic prior knowledge and understanding. If you find yourself needing to read further about these topics, a list of suggested titles is provided for convenience.</p><p nodeindex=\"21\">If you would like to learn how to write beautiful, structured and organized code, I believe this is the book for you.</p><h2 nodeindex=\"22\">Acknowledgments</h2><p nodeindex=\"23\">I will always be grateful for the talented technical reviewers who helped review and improve this book, including those from the community at large. The knowledge and enthusiasm they brought to the project was simply amazing. The official technical reviewers tweets and blogs are also a regular source of both ideas and inspiration and I wholeheartedly recommend checking them out.</p><ul nodeindex=\"25\"><li nodeindex=\"24\">Nicholas Zakas (<a href=\"http://nczonline.net/\" nodeindex=\"1775\">http://nczonline.net</a>,<a href=\"http://twitter.com/slicknet\" nodeindex=\"1776\">@slicknet</a>)</li><li nodeindex=\"26\">Andrée Hansson (<a href=\"http://andreehansson.se/\" nodeindex=\"1777\">http://andreehansson.se</a>,<a href=\"http://twitter.com/peolanha\" nodeindex=\"1778\">@peolanha</a>)</li><li nodeindex=\"27\">Luke Smith (<a href=\"http://lucassmith.name\" nodeindex=\"1779\">http://lucassmith.name</a>,<a href=\"http://twitter.com/ls_n\" nodeindex=\"1780\">@ls_n</a>)</li><li nodeindex=\"28\">Eric Ferraiuolo (<a href=\"http://ericf.me/\" nodeindex=\"1781\">http://ericf.me/</a>,<a href=\"https://twitter.com/ericf\" nodeindex=\"1782\">@ericf</a>)</li><li nodeindex=\"29\">Peter Michaux (<a href=\"http://michaux.ca\" nodeindex=\"1783\">http://michaux.ca</a>,<a href=\"http://twitter.com/petermichaux\" nodeindex=\"1784\">@petermichaux</a>)</li><li nodeindex=\"30\">Alex Sexton (<a href=\"http://alexsexton.com\" nodeindex=\"1785\">http://alexsexton.com</a>,<a href=\"http://twitter.com/slexaxton\" nodeindex=\"1786\">@slexaxton</a>)</li></ul><p nodeindex=\"31\">I would also like to thank Rebecca Murphey (<a href=\"http://rebeccamurphey.com\" nodeindex=\"1787\">http://rebeccamurphey.com</a>,<a href=\"http://twitter.com/rmurphey\" nodeindex=\"1788\">@rmurphey</a>) for providing the inspiration to write this book and more importantly, continue to make it both available on GitHub and via O'Reilly.</p><p nodeindex=\"32\">Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was putting together this publication.</p><h2 nodeindex=\"33\">Credits</h2><p nodeindex=\"34\">Whilst some of the patterns covered in this book were implemented based on personal experience, many of them have been previously identified by the JavaScript community. This work is as such the production of the combined experience of a number of developers. Similar to Stoyan Stefanov's logical approach to preventing interruption of the narrative with credits (in<em nodeindex=\"1789\">JavaScript Patterns</em>), I have listed credits and suggested reading for any content covered in the references section.</p><p nodeindex=\"35\">If any articles or links have been missed in the list of references, please accept my heartfelt apologies. If you contact me I'll be sure to update them to include you on the list.</p><h2 nodeindex=\"36\">Reading</h2><p nodeindex=\"37\">Whilst this book is targeted at both beginners and intermediate developers, a basic understanding of JavaScript fundamentals is assumed. Should you wish to learn more about the language, I am happy to recommend the following titles:</p><ul nodeindex=\"39\"><li nodeindex=\"38\"><em nodeindex=\"1790\">JavaScript: The Definitive Guide</em> by David Flanagan</li><li nodeindex=\"40\"><em nodeindex=\"1791\">Eloquent JavaScript</em> by Marijn Haverbeke</li><li nodeindex=\"41\"><em nodeindex=\"1792\">JavaScript Patterns</em> by Stoyan Stefanov</li><li nodeindex=\"42\"><em nodeindex=\"1793\">Writing Maintainable JavaScript</em> by Nicholas Zakas</li><li nodeindex=\"43\"><em nodeindex=\"1794\">JavaScript: The Good Parts</em> by Douglas Crockford</li></ul><h1 nodeindex=\"44\"><em nodeindex=\"1795\">Table Of Contents</em></h1><h1 id=\"introduction\" nodeindex=\"94\"><a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#introduction\" class=\"subhead-link\" nodeindex=\"1796\">#</a> Introduction</h1><p nodeindex=\"95\">One of the most important aspects of writing maintainable code is being able to notice the recurring themes in that code and optimize them. This is an area where knowledge of design patterns can prove invaluable.</p><p nodeindex=\"96\">In the first part of this book, we will explore the history and importance of design patterns which can really be applied to any programming language. If you're already sold on or are familiar with this history, feel free to skip to the chapter \"<a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#whatisapattern\" nodeindex=\"1797\">What is a Pattern?</a>\" to continue reading.</p><p nodeindex=\"97\">Design patterns can be traced back to the early work of an architect named<a href=\"http://www.wikiwand.com/en/Christopher_Alexander\" nodeindex=\"1798\" data-new-link=\"http://www.wikiwand.com/en/Christopher_Alexander\" data-noreplace=\"1\">Christopher Alexander</a>. He would often write publications about his experience in solving design issues and how they related to buildings and towns. One day, it occurred to Alexander that when used time and time again, certain design constructs lead to a desired optimal effect.</p><p nodeindex=\"98\">In collaboration with Sara Ishikawa and Murray Silverstein, Alexander produced a pattern language that would help empower anyone wishing to design and build at any scale. This was published back in 1977 in a paper titled \"A Pattern Language\", which was later released as a complete hardcover<a href=\"http://www.amazon.co.uk/Pattern-Language-Buildings-Construction-Environmental/dp/0195019199/ref=sr_1_1?s=books&ie=UTF8&qid=1329440685&sr=1-1&tag=rnwap-20\" nodeindex=\"1799\">book</a>.</p><p nodeindex=\"99\">Some 30 years ago, software engineers began to incorporate the principles Alexander had written about into the first documentation about design patterns, which was to be a guide for novice developers looking to improve their coding skills. It's important to note that the concepts behind design patterns have actually been around in the programming industry since its inception, albeit in a less formalized form.</p><p nodeindex=\"100\">One of the first and arguably most iconic formal works published on design patterns in software engineering was a book in 1995 called<em nodeindex=\"1800\">Design Patterns: Elements Of Reusable Object-Oriented Software</em>. This was written by<a href=\"http://www.wikiwand.com/en/Erich_Gamma\" nodeindex=\"1801\" data-new-link=\"http://www.wikiwand.com/en/Erich_Gamma\" data-noreplace=\"1\">Erich Gamma</a>,<a href=\"http://en.wikipedia.org/w/index.php?title=Richard_Helm&action=edit&redlink=1\" nodeindex=\"1802\" data-noreplace=\"1\">Richard Helm</a>,<a href=\"http://www.wikiwand.com/en/Ralph_Johnson\" nodeindex=\"1803\" data-new-link=\"http://www.wikiwand.com/en/Ralph_Johnson\" data-noreplace=\"1\">Ralph Johnson</a> and<a href=\"http://www.wikiwand.com/en/John_Vlissides\" nodeindex=\"1804\" data-new-link=\"http://www.wikiwand.com/en/John_Vlissides\" data-noreplace=\"1\">John Vlissides</a> - a group that became known as the Gang of Four (or GoF for short).</p><p nodeindex=\"101\">The GoF's publication is considered quite instrumental to pushing the concept of design patterns further in our field as it describes a number of development techniques and pitfalls as well as providing twenty-three core Object-Oriented design patterns frequently used around the world today. We will be covering these patterns in more detail in the section \"Categories of Design Patterns\".</p><p nodeindex=\"102\">In this book, we will take a look at a number of popular JavaScript design patterns and explore why certain patterns may be more suitable for your projects than others. Remember that patterns can be applied not just to vanilla JavaScript (i.e standard JavaScript code), but also to abstracted libraries such as<a href=\"http://jquery.com\" nodeindex=\"1805\">jQuery</a> or<a href=\"http://dojotoolkit.org\" nodeindex=\"1806\">dojo</a> as well. Before we begin, let’s look at the exact definition of a \"pattern\" in software design.</p><h1 id=\"whatisapattern\" nodeindex=\"103\">What is a Pattern?</h1><p nodeindex=\"104\">A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.</p><p nodeindex=\"105\">So, why is it important to understand patterns and be familiar with them? Design patterns have three main benefits:</p><p nodeindex=\"111\">Patterns are<strong nodeindex=\"1807\">not</strong> an exact solution. It’s important that we remember the role of a pattern is merely to provide us with a solution scheme. Patterns don’t solve all design problems nor do they replace good software designers, however, they<strong nodeindex=\"1808\">do</strong> support them. Next we’ll take a look at some of the other advantages patterns have to offer.</p><ul nodeindex=\"113\"><li nodeindex=\"112\"><strong nodeindex=\"1809\">Reusing patterns assists in preventing minor issues that can cause major problems in the application development process.</strong> What this means is when code is built on proven patterns, we can afford to spend less time worrying about the structure of our code and more time focusing on the quality of our overall solution. This is because patterns can encourage us to code in a more structured and organized fashion avoiding the need to refactor it for cleanliness purposes in the future.</li></ul><ul nodeindex=\"115\"><li nodeindex=\"114\"><strong nodeindex=\"1810\">Patterns can provide generalized solutions which are documented in a fashion that doesn't require them to be tied to a specific problem.</strong> This generalized approach means that regardless of the application (and in many cases the programming language) we are working with, design patterns can be applied to improve the structure of our code.</li><li nodeindex=\"116\"><strong nodeindex=\"1811\">Certain patterns can actually decrease the overall file-size footprint of our code by avoiding repetition.</strong> By encouraging developers to look more closely at their solutions for areas where instant reductions in<span id=\"internal-source-marker_0.982673292361492\" nodeindex=\"1812\">repetition</span> can be made, e.g. reducing the number of functions performing similar processes in favor of a single generalized function, the overall size of our codebase can be decreased. This is also known as making code more<em nodeindex=\"1813\">DRY</em>.</li><li nodeindex=\"117\"><strong nodeindex=\"1814\">Patterns add to a developer's vocabulary, which makes communication faster.</strong></li><li nodeindex=\"118\"><strong nodeindex=\"1815\">Patterns that are frequently used can be improved over time by harnessing the collective experiences other developers using those patterns contribute back to the design pattern community.</strong> In some cases this leads to the creation of entirely new design patterns whilst in others it can lead to the provision of improved guidelines on how specific patterns can be best used. This can ensure that pattern-based solutions continue to become more robust than ad-hoc solutions may be.</li></ul><h3 nodeindex=\"119\">We already use patterns everyday</h3><p nodeindex=\"120\">To understand how useful patterns can be, let's review a very simple element selection problem that the jQuery library solves for us.</p><p nodeindex=\"121\">Imagine that we have a script where for each DOM element found on a page with class \"foo\" we wish to increment a counter. What's the most efficient way to query for this collection of elements? Well, there are a few different ways this problem could be tackled:</p><ol nodeindex=\"123\"><li nodeindex=\"122\">Select all of the elements in the page and then store references to them. Next, filter this collection and use regular expressions (or another means) to only store those with the class \"foo\".</li><li nodeindex=\"124\">Use a modern native browser feature such as<code nodeindex=\"1816\">querySelectorAll()</code> to select all of the elements with the class \"foo\".</li><li nodeindex=\"125\">Use a native feature such as<code nodeindex=\"1817\">getElementsByClassName()</code> to similarly get back the desired collection.</li></ol><p nodeindex=\"126\">So, which of these options is the fastest? It's actually option 3. by a factor of 8-10 times the<a href=\"http://jsperf.com/getelementsbyclassname-vs-queryselectorall/5\" nodeindex=\"1818\">alternatives</a>. In a real-world application however, 3. will not work in versions of Internet Explorer below 9 and thus it's necessary to use 1. where both 2. and 3. aren't supported.</p><p nodeindex=\"127\">Developers using jQuery don't have to worry about this problem however, as it's luckily abstracted away for us using the<em nodeindex=\"1819\">Facade</em> pattern. As we'll review in more detail later, this pattern provides a simple set of abstracted interfaces (e.g<code nodeindex=\"1820\">$el.css()</code>,<code nodeindex=\"1821\">$el.animate()</code>) to several more complex underlying bodies of code. As we've seen, this means less time having to be concerned about implementation level details.</p><p nodeindex=\"128\">Behind the scenes, the library simply opts for the most optimal approach to selecting elements depending on what our current browser supports and we just consume the abstraction layer.</p><p nodeindex=\"129\">We're probably all also familiar with jQuery's<code nodeindex=\"1822\">$(\"selector\")</code>. This is significantly more easy to use for selecting HTML elements on a page versus having to manually opt for<code nodeindex=\"1823\">getElementById()</code>,<code nodeindex=\"1824\">getElementsByClassName()</code>,<code nodeindex=\"1825\">getElementByTagName</code> and so on.</p><p nodeindex=\"130\">Although we know that<code nodeindex=\"1826\">querySelectorAll()</code> attempts to solve this problem, compare the effort involved in using jQuery's Facade interfaces vs. selecting the most optimal selection paths ourselves. There's no contest! Abstractions using patterns can offer real-world value.</p><p nodeindex=\"131\">We'll be looking at this and more design patterns later on in the book.</p><h1 id=\"patternity\" nodeindex=\"132\">\"Pattern\"-ity Testing, Proto-Patterns & The Rule Of Three</h1><p nodeindex=\"133\">Remember that not every algorithm, best practice or solution represents what might be considered a complete pattern. There may be a few key ingredients here that are missing and the pattern community is generally wary of something claiming to be one unless it has been heavily vetted. Even if something is presented to us which<strong nodeindex=\"1827\">appears</strong> to meet the criteria for a pattern, it should not be considered one until it has undergone suitable periods of scrutiny and testing by others.</p><p nodeindex=\"134\">Looking back upon the work by Alexander once more, he claims that a pattern should both be a process and a \"thing\". This definition is obtuse on purpose as he follows by saying that it is the process which should create the \"thing\". This is a reason why patterns generally focus on addressing a visually identifiable structure i.e we should be able to visually depict (or draw) a picture representing the structure that placing the pattern into practice results in.</p><p nodeindex=\"135\">In studying design patterns, it's not irregular to come across the term \"proto-pattern\". What is this? Well, a pattern that has not yet been known to pass the \"pattern\"-ity tests is usually referred to as a proto-pattern. Proto-patterns may result from the work of someone that has established a particular solution that is worthy of sharing with the community, but may not have yet had the opportunity to have been vetted heavily due to its very young age.</p><p nodeindex=\"136\">Alternatively, the individual(s) sharing the pattern may not have the time or interest of going through the \"pattern\"-ity process and might release a short description of their proto-pattern instead. Brief descriptions or snippets of this type of pattern are known as patlets.</p><p nodeindex=\"137\">The work involved in fully documenting a qualified pattern can be quite daunting. Looking back at some of the earliest work in the field of design patterns, a pattern may be considered \"good\" if it does the following:</p><ul type=\"disc\" nodeindex=\"139\"><li nodeindex=\"138\"><strong nodeindex=\"1828\">Solves a particular problem</strong>: Patterns are not supposed to just capture principles or strategies. They need to capture solutions. This is one of the most essential ingredients for a good pattern.</li><li nodeindex=\"140\"><strong nodeindex=\"1829\">The solution to this problem cannot be obvious</strong>: We can find that problem-solving techniques often attempt to derive from well-known first principles. The best design patterns usually provide solutions to problems indirectly - this is considered a necessary approach for the most challenging problems related to design.</li><li nodeindex=\"141\"><strong nodeindex=\"1830\">The concept described must have been proven</strong>: Design patterns require proof that they function as described and without this proof the design cannot be seriously considered. If a pattern is highly speculative in nature, only the brave may attempt to use it.</li><li nodeindex=\"142\"><strong nodeindex=\"1831\">It must describe a relationship</strong>: In some cases it may appear that a pattern describes a type of module. Although an implementation may appear this way, the official description of the pattern must describe much deeper system structures and mechanisms that explain its relationship to code.</li></ul><p nodeindex=\"143\">We would be forgiven for thinking that a proto-pattern which fails to meet guidelines isn't worth learning from, however, this is far from the truth. Many proto-patterns are actually quite good. I’m not saying that all proto-patterns are worth looking at, but there are quite a few useful ones in the wild that could assist us with future projects. Use best judgment with the above list in mind and you’ll be fine in your selection process.</p><p nodeindex=\"144\">One of the additional requirements for a pattern to be valid is that they display some recurring phenomenon. This is often something that can be qualified in at least three key areas, referred to as the<em nodeindex=\"1832\">rule of three</em>. To show recurrence using this rule, one must demonstrate:</p><ol start=\"1\" type=\"1\" nodeindex=\"146\"><li nodeindex=\"145\"><strong nodeindex=\"1833\">Fitness of purpose</strong> - how is the pattern considered successful?</li><li nodeindex=\"147\"><strong nodeindex=\"1834\">Usefulness</strong> - why is the pattern considered successful?</li><li nodeindex=\"148\"><strong nodeindex=\"1835\">Applicability</strong> - is the design worthy of being a pattern because it has wider applicability? If so, this needs to be explained. When reviewing or defining a pattern, it is important to keep the above in mind.</li></ol><h1 id=\"designpatternstructure\" nodeindex=\"149\"><a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternstructure\" class=\"subhead-link\" nodeindex=\"1836\">#</a> The Structure Of A Design Pattern</h1><p nodeindex=\"150\">You may be curious about how a pattern author might approach outlining structure, implementation and purpose of a new pattern. A pattern is initially presented in the form of a<strong nodeindex=\"1837\">rule</strong> that establishes a relationship between:</p><ul nodeindex=\"152\"><li nodeindex=\"151\">A<strong nodeindex=\"1838\">context</strong></li><li nodeindex=\"153\">A system of<strong nodeindex=\"1839\">forces</strong> that arises in that context and</li><li nodeindex=\"154\">A<strong nodeindex=\"1840\">configuration</strong> that allows these forces to resolve themselves in context</li></ul><p nodeindex=\"155\">With this in mind, let’s now take a look at a summary of the component elements for a design pattern. A design pattern should have a:</p><ul nodeindex=\"157\"><li nodeindex=\"156\"><strong nodeindex=\"1841\">Pattern name</strong> and a<strong nodeindex=\"1842\">description</strong></li><li nodeindex=\"158\"><strong nodeindex=\"1843\">Context outline</strong> – the contexts in which the pattern is effective in responding to the users needs.</li><li nodeindex=\"159\"><strong nodeindex=\"1844\">Problem statement</strong> – a statement of the problem being addressed so we can understand the intent of the pattern.</li><li nodeindex=\"160\"><strong nodeindex=\"1845\">Solution</strong> – a description of how the user’s problem is being solved in an understandable list of steps and perceptions.</li><li nodeindex=\"161\"><strong nodeindex=\"1846\">Design</strong> – a description of the pattern’s design and in particular, the user’s behavior in interacting with it</li><li nodeindex=\"162\"><strong nodeindex=\"1847\">Implementation</strong> – a guide to how the pattern would be implemented</li><li nodeindex=\"163\"><strong nodeindex=\"1848\">Illustrations</strong> – a visual representation of classes in the pattern (e.g. a diagram))</li><li nodeindex=\"164\"><strong nodeindex=\"1849\">Examples</strong> – an implementation of the pattern in a minimal form</li><li nodeindex=\"165\"><strong nodeindex=\"1850\">Co-requisites</strong> – what other patterns may be needed to support use of the pattern being described?</li><li nodeindex=\"166\"><strong nodeindex=\"1851\">Relations</strong> – what patterns does this pattern resemble? does it closely mimic any others?</li><li nodeindex=\"167\"><strong nodeindex=\"1852\">Known usage</strong> – is the pattern being used in the<em nodeindex=\"1853\">wild</em>? If so, where and how?</li><li nodeindex=\"168\"><strong nodeindex=\"1854\">Discussions</strong> – the team or author’s thoughts on the exciting benefits of the pattern</li></ul><p nodeindex=\"169\">Design patterns are quite a powerful approach to getting all of the developers in an organization or team on the same page when creating or maintaining solutions. If considering working on a pattern of your own, remember that although they may have a heavy initial cost in the planning and write-up phases, the value returned from that investment can be quite worth it. Always research thoroughly before working on new patterns however, as you may find it more beneficial to use or build on top of existing proven patterns than starting afresh.</p><h1 id=\"writingdesignpatterns\" nodeindex=\"170\"><a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#writingdesignpatterns\" class=\"subhead-link\" nodeindex=\"1855\">#</a> Writing Design Patterns</h1><p nodeindex=\"171\">Although this book is aimed at those new to design patterns, a fundamental understanding of how a design pattern is written can offer a number of useful benefits. For starters, we can gain a deeper appreciation for the reasoning behind why a pattern is needed. We can also learn how to tell if a pattern (or proto-pattern) is up to scratch when reviewing it for our own needs.</p><p nodeindex=\"172\">Writing good patterns is a challenging task. Patterns not only need to (ideally) provide a substantial quantity of reference material for end-users, but they also need to be able to defend why they are necessary.</p><p nodeindex=\"173\">Having read the previous section on<em nodeindex=\"1856\">what</em> a pattern is, we may think that this in itself is enough to help us identify patterns we see in the wild. This is actually not completely true. It's not always clear if a piece of code we're looking at is following a set pattern or just accidentally happens to appear like it does.</p><p nodeindex=\"174\">When we're looking at a body of code we think may be using a pattern, we should consider writing down some of the aspects of the code that we believe falls under a particular existing pattern or set of patterns.</p><p nodeindex=\"175\">In many cases of pattern-analysis we can find that we're just looking at code that follows good principles and design practices that could happen to overlap with the rules for a pattern by accident. Remember - solutions in which neither interactions nor defined rules appear are<em nodeindex=\"1857\">not</em> patterns.</p><p nodeindex=\"176\">If interested in venturing down the path of writing your own design patterns I recommend learning from others who have already been through the process and done it well. Spend time absorbing the information from a number of different design pattern descriptions and take in what’s meaningful to you.</p><p nodeindex=\"177\">Explore structure and semantics - this can be done by examining the interactions and context of the patterns you are interested in so you can identify the principles that assist in organizing those patterns together in useful configurations.</p><p nodeindex=\"178\">Once we've exposed ourselves to a wealth of information on pattern literature, we may wish to begin writing our pattern using an<em nodeindex=\"1858\">existing</em> format and see if we can brainstorm new ideas for improving it or integrating our ideas in there.</p><p nodeindex=\"179\">An example of a developer that did this is in recent years is Christian Heilmann, who took the existing<em nodeindex=\"1859\">Module</em> pattern and made some fundamentally useful changes to it to create the<em nodeindex=\"1860\">Revealing Module</em> pattern (this is one of the patterns covered later in this book).</p><p nodeindex=\"180\">The following are tips I would suggest if interested in creating a new design pattern:</p><ul type=\"disc\" nodeindex=\"182\"><li nodeindex=\"181\"><strong nodeindex=\"1861\">How practical is the pattern?</strong>: Ensure the pattern describes proven solutions to recurring problems rather than just speculative solutions which haven’t been qualified.</li><li nodeindex=\"183\"><strong nodeindex=\"1862\">Keep best practices in mind:</strong> The design decisions we make should be based on principles we derive from an understanding of best practices.</li><li nodeindex=\"184\"><strong nodeindex=\"1863\">Our design patterns should be transparent to the user</strong>: Design patterns should be entirely transparent to any type of user-experience. They are primarily there to serve the developers using them and should not force changes to behavior in the user-experience that would not be incurred without the use of a pattern.</li><li nodeindex=\"185\"><strong nodeindex=\"1864\">Remember that originality is<em nodeindex=\"1865\">not</em> key in pattern design</strong>: When writing a pattern, we do not need to be the original discoverer of the solutions being documented nor do you have to worry about our design overlapping with minor pieces of other patterns. If the approach is strong enough to have broad useful applicability, it has a chance of being recognized as a valid pattern.</li><li nodeindex=\"186\"><strong nodeindex=\"1866\">Pattern need a strong set of examples:</strong> A good pattern description needs to be followed by an equally strong set of examples demonstrating the successful application of our pattern. To show broad usage, examples that exhibit good design principles are ideal.</li></ul><p nodeindex=\"187\">Pattern writing is a careful balance between creating a design that is general, specific and above all, useful. Try to ensure that if writing a pattern you cover the widest possible areas of application and you should be fine. I hope that this brief introduction to writing patterns has given you some insights that will assist your learning process for the next sections of this book.</p><h1 id=\"antipatterns\" nodeindex=\"188\"><a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#antipatterns\" class=\"subhead-link\" nodeindex=\"1867\">#</a> Anti-Patterns</h1><p nodeindex=\"189\">If we consider that a pattern represents a best practice, an anti-pattern represents a lesson that has been learned. The term anti-patterns was coined in 1995 by Andrew Koenig in the November C++ Report that year, inspired by the GoF's book<em nodeindex=\"1868\">Design Patterns</em>. In Koenig’s report, there are two notions of anti-patterns that are presented. Anti-Patterns:</p><ul type=\"disc\" nodeindex=\"191\"><li nodeindex=\"190\">Describe a<em nodeindex=\"1869\">bad</em> solution to a particular problem which resulted in a bad situation occurring</li><li nodeindex=\"192\">Describe<em nodeindex=\"1870\">how</em> to get out of said situation and how to go from there to a good solution</li></ul><p nodeindex=\"193\">On this topic, Alexander writes about the difficulties in achieving a good balance between good design structure and good context:</p><p nodeindex=\"194\"><em nodeindex=\"1871\">“These notes are about the process of design; the process of inventing physical things which display a new physical order, organization, form, in response to function.…every design problem begins with an effort to achieve fitness between two entities: the form in question and its context. The form is the solution to the problem; the context defines the problem”.</em></p><p nodeindex=\"195\">While it’s quite important to be aware of design patterns, it can be equally important to understand anti-patterns. Let us qualify the reason behind this. When creating an application, a project’s life-cycle begins with construction however once you’ve got the initial release done, it needs to be maintained. The quality of a final solution will either be<em nodeindex=\"1872\">good</em> or<em nodeindex=\"1873\">bad</em>, depending on the level of skill and time the team have invested in it. Here<em nodeindex=\"1874\">good</em> and<em nodeindex=\"1875\">bad</em> are considered in context - a ‘perfect’ design may qualify as an anti-pattern if applied in the wrong context.</p><p nodeindex=\"196\">The bigger challenges happen after an application has hit production and is ready to go into maintenance mode. A developer working on such a system who hasn’t worked on the application before may introduce a<em nodeindex=\"1876\">bad</em> design into the project by accident. If said<em nodeindex=\"1877\">bad</em> practices are created as anti-patterns, they allow developers a means to recognize these in advance so that they can avoid common mistakes that can occur - this is parallel to the way in which design patterns provide us with a way to recognize common techniques that are<em nodeindex=\"1878\">useful.</em></p><p nodeindex=\"197\">To summarize, an anti-pattern is a bad design that is worthy of documenting. Examples of anti-patterns in JavaScript are the following:</p><ul type=\"disc\" nodeindex=\"199\"><li nodeindex=\"198\">Polluting the global namespace by defining a large number of variables in the global context</li><li nodeindex=\"200\">Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of<code nodeindex=\"1879\">eval()</code> internally.</li><li nodeindex=\"201\">Modifying the<code nodeindex=\"1880\">Object</code> class prototype (this is a particularly bad anti-pattern)</li><li nodeindex=\"202\">Using JavaScript in an inline form as this is inflexible</li><li nodeindex=\"203\">The use of document.write where native DOM alternatives such as document.createElement are more appropriate. document.write has been grossly misused over the years and has quite a few disadvantages including that if