master bff021b5923c cached
121 files
467.8 KB
134.7k tokens
41 symbols
1 requests
Download .txt
Showing preview only (501K chars total). Download the full file or copy to clipboard to get everything.
Repository: chuanxshi/javascript-patterns
Branch: master
Commit: bff021b5923c
Files: 121
Total size: 467.8 KB

Directory structure:
gitextract_ubd058uh/

├── README.md
├── cn/
│   └── index.html
├── code-reuse-patterns/
│   ├── borrowing-methods.html
│   ├── cp1-default.html
│   ├── cp2-rent-a-constructor.html
│   ├── cp3-rent-and-set-prototype.html
│   ├── cp4-share-the-prototype.html
│   ├── cp5-a-temporary-constructor.html
│   ├── inheritance-by-copying-properties.html
│   ├── klass.html
│   ├── mix-ins.html
│   └── prototypal-inheritance.html
├── css/
│   └── style.css
├── design-patterns/
│   ├── builder.html
│   ├── chain-of-responsibility.html
│   ├── command.html
│   ├── decorator.html
│   ├── facade.html
│   ├── factory.html
│   ├── iterator.html
│   ├── mediator.html
│   ├── multiton.html
│   ├── observer.html
│   ├── proxy.html
│   ├── singleton.html
│   ├── strategy.html
│   └── visitor.html
├── dom-and-browser/
│   └── event-handling.html
├── function-patterns/
│   ├── callback.html
│   ├── callbacks-and-scope.html
│   ├── configuration-objects.html
│   ├── currying.html
│   ├── enforcing-new-in-constructors.html
│   ├── function-call.html
│   ├── immediate-functions.html
│   ├── immediate-object-initialization.html
│   ├── init-time-branching.html
│   ├── memoization.html
│   ├── partial-application.html
│   ├── returning-functions.html
│   ├── self-defining-functions.html
│   └── self-overwrite.html
├── general-patterns/
│   ├── access-to-global-object.html
│   ├── avoiding-eval.html
│   ├── avoiding-implied-typecasting.html
│   ├── built-in-prototypes.html
│   ├── conditionals.html
│   ├── for-in-loops.html
│   ├── for-loops.html
│   ├── function-declarations.html
│   ├── global-import.html
│   ├── globals.html
│   ├── hoisting.html
│   ├── iife-for-loop.html
│   ├── map-and-filter-by-reduce.html
│   ├── minimizing-globals.html
│   ├── parseint.html
│   ├── shim-sniffing.html
│   ├── single-var-pattern.html
│   └── switch-pattern.html
├── img/
│   └── .gitignore
├── index.html
├── jquery-patterns/
│   ├── append.html
│   ├── cache-selector.html
│   ├── context-and-find.html
│   ├── data.html
│   ├── decending-from-id.html
│   ├── detach.html
│   ├── event-delegation.html
│   ├── left-and-right.html
│   ├── pubsub-callback.html
│   ├── pubsub-custom-events.html
│   ├── pubsub-observable.html
│   ├── pubsub-plugin.html
│   ├── requery.html
│   ├── specific-when-needed.html
│   ├── universal-selector.html
│   └── window-scroll-event.html
├── jquery-plugin-patterns/
│   ├── amd-commonjs/
│   │   ├── pluginCore.js
│   │   ├── pluginExtension.js
│   │   └── usage.html
│   ├── basic.html
│   ├── best-options.html
│   ├── custom-events.html
│   ├── extend.html
│   ├── highly-configurable-mutable.html
│   ├── jquery-mobile-ui-widget-factory.html
│   ├── lightweight.html
│   ├── namespaced-starter.html
│   ├── prototypal-inheritance.html
│   ├── ui-widget-factory-bridge.html
│   ├── ui-widget-factory-mobile.html
│   ├── ui-widget-factory.html
│   └── ui-widget-requirejs-module.html
├── js/
│   ├── libs/
│   │   └── jquery-1.6.4.js
│   ├── plugins.js
│   └── script.js
├── literals-and-constructors/
│   ├── array-literal.html
│   ├── enforcing-new.html
│   ├── json.html
│   ├── object-literal.html
│   ├── primitive-wrappers.html
│   └── regular-expression-literal.html
└── object-creation-patterns/
    ├── chaining.html
    ├── declaring-dependencies.html
    ├── inheritence.html
    ├── module.html
    ├── module2.html
    ├── module3-augmentation.html
    ├── module4-loose-augmentation.html
    ├── module5-tight-augmentation.html
    ├── module6-clone-inheritance.html
    ├── module7-cross-file.html
    ├── namespace.html
    ├── object-constants.html
    ├── private-properties-and-methods.html
    ├── revelation.html
    ├── sandbox.html
    ├── static-members.html
    ├── sub-module.html
    └── sugar-method.html

================================================
FILE CONTENTS
================================================

================================================
FILE: README.md
================================================
#JavaScript Patterns

<img src="http://shichuan.github.io/javascript-patterns/img/js-patterns.png" alt="JS Patterns" title="JS Patterns" />
<br />
Project page at: <a href="http://shichuan.github.io/javascript-patterns" target="_blank">http://shichuan.github.io/javascript-patterns</a>



================================================
FILE: cn/index.html
================================================
<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!-- Consider adding a manifest.appcache: h5bp.com/d/Offline -->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">

  <!-- Use the .htaccess and remove these lines to avoid edge case issues.
       More info: h5bp.com/b/378 -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>JavaScript的模式和反模式集合</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- Mobile viewport optimized: h5bp.com/viewport -->
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <!-- Place favicon.ico and apple-touch-icon.png in the root directory: mathiasbynens.be/notes/touch-icons -->
  <link href='http://fonts.googleapis.com/css?family=Tinos:400,700,400italic' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="../css/style.css">
  
  <!-- More ideas for your <head> here: h5bp.com/d/head-Tips -->

  <!-- All JavaScript at the bottom, except this Modernizr build incl. Respond.js
       Respond is a polyfill for min/max-width media queries. Modernizr enables HTML5 elements & feature detects; 
       for optimal performance, create your own custom Modernizr build: www.modernizr.com/download/ -->
  <script src="../js/libs/modernizr-2.0.6.min.js"></script>
</head>

<body>
  <a class="fork" href="https://github.com/shichuan/javascript-patterns">
    <img src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
   </a>
  <header>
    <div class="clearfix">
      <h1>JavaScript的模式集合</h1>
      <div id="btns">
      <span  class='st_sina_hcount' displayText='Sina'></span><span  class='st_baidu_hcount' displayText='Baidu'></span><span  class='st_twitter_hcount' displayText='Tweet'></span><span  class='st_facebook_hcount' displayText='Facebook'></span><span  class='st_fblike_hcount' ></span><span  class='st_plusone_hcount' ></span>
      </div>
    </div>
    <img src="../img/js-patterns-cn.png" alt="JS Patterns" title="JS Patterns" />
  </header>
  <div role="main">
    <section id="intro">
      <p>A JavaScript pattern and antipattern code collection that covers function patterns, jQuery patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns (<em>upcoming</em>), code reuse patterns (<em>upcoming</em>), DOM and browser patterns (<em>upcoming</em>).</p>
      <p>Weekly roundups (pattern updates) will be regularly <a href="http://twitter.com/shichuan">tweeted</a>.</p>
    </section>
    <section>
      <h2>Function Patterns</h2>
      <h3>API Patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/callback.html" target="_blank">Callback patterns</a> - when you pass function A to function B as a parameter, function A is a callback function</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/configuration-objects.html" target="_blank">Configuration objects </a>- keep control of function arguments and makes it easily configurable</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/returning-functions.html" target="_blank">Returning functions </a>- one function returns another function or create another function on-demand</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html" target="_blank">Currying</a> - used to create new functions dynamically by partially applying a set of arguments</li>
      </ul>
      
      <h3>Initialization patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/immediate-functions.html" target="_blank">Immediate functions</a> - syntax that enables function execution as soon as it is defined</li> 
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/immediate-object-initialization.html" target="_blank">Immediate object initialization</a> - this pattern is mainly suitable for one-off tasks</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/init-time-branching.html" target="_blank">Init-time branching</a> - branch code once during initlization initialization</li>
      </ul>
      
      <h3>Performance patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/memoization.html">Memoization</a> - use function properties to avoid repeated computation</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/self-defining-functions.html">Self-defining functions</a> - self-overwrite with new bodies to do less work from the second invocation and after</li>
      </ul>
    </section>
    
    <section>
      <h2>jQuery Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/requery.html" target="_blank">requery</a> - avoid requery by using jQuery chaining</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/append.html" target="_blank">append</a> - use string concatenate and set innerHTML</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/data.html" target="_blank">data</a> - pattern and antipattern of using data</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/context-and-find.html" target="_blank">context and find</a> - use find over context</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/detach.html" target="_blank">detach</a> - take element off the DOM while manipulating them</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/event-delegation.html" target="_blank">event delegation</a> - event delegation pattern and antipattern</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/cache-selector.html" target="_blank">selector cache</a> - using selector cache to avoid requery</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/window-scroll-event.html" target="_blank">window scroll event</a> -  avoid attaching handlers to the window scroll event</li>
      </ul>
      <h3>Selector</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/left-and-right.html" target="_blank">Left and Right</a> - specific on the right, light on the left</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/decending-from-id.html" target="_blank">Decending from id</a> - be more specific</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/universal-selector.html" target="_blank">Universal Selector</a> - use of universal selector</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/specific-when-needed.html" target="_blank">Be Specific when Needed</a> - be specific only when needed</li>
      </ul>
    </section>
    
    <section>
      <h2>Literals and Constructors Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/object-literal.html" target="_blank">Object literal</a> - use the simpler and reliable object literal instead of new Object();</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/enforcing-new.html" target="_blank">Enforcing new</a> - when you forget `new`, `this` inside the constructor will point to the global object</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/array-literal.html" target="_blank">Array literal</a> - use array literal notation to avoid potential errors when creating dynamic arrays at runtime</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/json.html" target="_blank">Working with JSON</a> - use library from JSON.org, YUI, jQuery instead of eval for parsing</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/primitive-wrappers.html" target="_blank">Primitive wrappers</a> - try to use the primitive without wrapper</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/regular-expression-literal.html" target="_blank">Regular expression literal</a> - try to use the shorter literal notation</li>
      </ul>
    </section>
    
    <section>
      <h2>Design Patterns</h2>
      <h3>Creational</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/builder.html" target="_blank">Builder</a> - constructs complex objects by separating construction and representation</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/factory.html" target="_blank">Factory method</a> - creates objects without specifying the exact class to create</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/singleton.html" target="_blank">Singleton</a> - restricts object creation for a class to only one instance</li>
      </ul>
      <h3>Structural</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/decorator.html" target="_blank">Decorator</a> - dynamically adds/overrides behaviour in an existing method of an object</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/facade.html" target="_blank">Facade</a> - provides a simplified interface to a large body of code</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/proxy.html" target="_blank">Proxy</a> - provides a placeholder for another object to control access, reduce cost, and reduce complexity</li>
      </ul>
      <h3>Behavioral</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/chain-of-responsibility.html" target="_blank">Chain of responsibility</a> - delegates commands to a chain of processing objects</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/command.html" target="_blank">Command</a> - creates objects which encapsulate actions and parameters</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/iterator.html" target="_blank">Iterator</a> - implements a specialized language</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/mediator.html" target="_blank">Mediator</a> - allows loose coupling between classes by being the only class that has detailed knowledge of their methods</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/observer.html" target="_blank">Observer</a> - is a publish/subscribe pattern which allows a number of observer objects to see an event</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/strategy.html" target="_blank">Strategy</a> - allows one of a family of algorithms to be selected on-the-fly at runtime</li>
      </ul>
    </section>
    
    <section>
      <h2>General Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/minimizing-globals.html" target="_blank">Minimizing Globals</a> - create and access a global variable in a browser environment</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/globals.html" target="_blank">The Problem with Globals</a> - various problems with globals</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/access-to-global-object.html" target="_blank">Access to the Global Object</a> - access the global object without hard-coding the identifier window</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/single-var-pattern.html" target="_blank">Single var Pattern</a> - use one var statement and declare multiple variables</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/hoisting.html" target="_blank">Hoisting</a> - var statements anywhere in a function act as if the variables were declared at the top of the function</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/for-loops.html" target="_blank">for loops</a> - optimized for loops</li> 
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/for-in-loops.html" target="_blank">for-in loops</a> - optimized for-in loops</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/built-in-prototypes.html" target="_blank">(Not) Augmenting Built-in Prototypes</a> - only augment built-in prototypes when certain conditions are met</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/switch-pattern.html" target="_blank">switch Pattern</a> - improve the readability and robustness of your switch statements</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/avoiding-implied-typecasting.html" target="_blank">Implied Typecasting</a> - avoid implied typecasting</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/avoiding-eval.html" target="_blank">Avoiding eval()</a> - avoid using eval()</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/parseint.html" target="_blank">Number Conversions with parseInt()</a> - use the second radix parameter</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/conditionals.html" target="_blank">Conditionals</a> - pattern and antipattern of using if else</li>
      </ul>
    </section>
    
    <section>
      <h2><em>References</em></h2>
      <ol>    
        <li>
        The Essentials of Writing High Quality JavaScript<br />
        <a href="http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/" target="_blank">http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/</a>
        </li>
        <li>
        JSPatterns<br />
        <a href="http://www.jspatterns.com/" target="_blank">http://www.jspatterns.com/</a>
        </li>
        <li>
        jQuery Anti-Patterns for Performance & Compression<br />
        <a href="http://paulirish.com/2009/perf/" target="_blank">http://paulirish.com/2009/perf/</a>
        </li>
        <li>
        How DRY Affects JavaScript Performance<br />
        <a href="http://velocityconf.com/velocityeu/public/schedule/detail/21634" target="_blank">http://velocityconf.com/velocityeu/public/schedule/detail/21634</a>
        </li>
        <li>
        Object Oriented JavaScript<br />
        <a href="http://www.packtpub.com/object-oriented-javascript/book" target="_blank">http://www.packtpub.com/object-oriented-javascript/book</a>
        </li>
        <li>
        JavaScript Patterns<br />
        <a href="http://shop.oreilly.com/product/9780596806767.do" target="_blank">http://shop.oreilly.com/product/9780596806767.do</a>
        </li>
        <li>
        JavaScript: The Good Parts<br />
        <a href="http://shop.oreilly.com/product/9780596517748.do" target="_blank">http://shop.oreilly.com/product/9780596517748.do</a>
        </li>
        <li>
        Pro JavaScript Design Patterns<br />
        <a href="http://jsdesignpatterns.com/" target="_blank">http://jsdesignpatterns.com/</a>
        </li>
        <li>
        Essential JavaScript Design Patterns For Beginners, Volume 1.<br />
        <a href="http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/" target="_blank">http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/</a>
        </li>
        <li>
        Eloquent JavaScript<br />
        <a href="http://eloquentjavascript.net/" target="_blank">http://eloquentjavascript.net/</a>
        </li>
      </ol>
    </section>
  </div>
  <footer>
    by <a href="http://twitter.com/#!/shichuan">@shichuan</a>
  </footer>


  <!-- JavaScript at the bottom for fast page loading -->

  <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
  <script>window.jQuery || document.write('<script src="../js/libs/jquery-1.6.4.min.js"><\/script>')</script>


  <!-- scripts concatenated and minified via build script -->
  <script type="text/javascript">var switchTo5x=true;</script><script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script><script type="text/javascript">stLight.options({publisher:'44fc3536-fd12-4c07-970d-6654da9a2d6c'});</script>
  <!-- end scripts -->


  <!-- Asynchronous Google Analytics snippet. Change UA-XXXXX-X to be your site's ID.
       mathiasbynens.be/notes/async-analytics-snippet -->
  <script>
    var _gaq=[['_setAccount','UA-2773745-18'],['_trackPageview'],['_trackPageLoadTime']];
    (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
    g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
    s.parentNode.insertBefore(g,s)}(document,'script'));
  </script>

  <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6.
       chromium.org/developers/how-tos/chrome-frame-getting-started -->
  <!--[if lt IE 7 ]>
    <script defer src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script>
    <script defer>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script>
  <![endif]-->

</body>
</html>


================================================
FILE: code-reuse-patterns/borrowing-methods.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Borrowing Methods
			 Description: reuse one or two methods of an existing object without forming a parent-child relationship with that object
			 */

			function f() {
				var args = [].slice.call(arguments, 1, 3);
				return args;
			}

			var one = {
				name:'object',
				say:function (greet) {
					return greet + ', ' + this.name;
				}
			};

			// test
			console.log(one.say('hi')); // "hi, object"

			var two = {
				name:'another object'
			};
			
			// apply two to original object one.
			console.log(one.say.apply(two, ['hello'])); // "hello, another object"

			// assigning to a variable
			// `this` will point to the global object
			var say = one.say;
			console.log(say('hoho')); // "hoho, undefined"

			// passing as a callback
			var yetanother = {
				name:'Yet another object',
				method:function (callback) {
					return callback('Hola');
				}
			};
			console.log(yetanother.method(one.say)); // "Hola, undefined"

			function bind(o, m) {
				return function () {
					return m.apply(o, [].slice.call(arguments));
				};
			}

			var twosay = bind(two, one.say);
			console.log(twosay('yo')); // "yo, another object"


			// ECMAScript 5 adds a method bind() to Function.prototype, making it just as easy to use as apply() and call().

			if (typeof Function.prototype.bind === 'undefined') {
				Function.prototype.bind = function (thisArg) {
					var fn = this,
							slice = Array.prototype.slice,
							args = slice.call(arguments, 1);
					return function () {
						return fn.apply(thisArg, args.concat(slice.call(arguments)));
					};
				};
			}

			var twosay2 = one.say.bind(two);
			console.log(twosay2('Bonjour')); // "Bonjour, another object"

			var twosay3 = one.say.bind(two, 'Enchanté');
			console.log(twosay3()); // "Enchanté, another object"


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>


================================================
FILE: code-reuse-patterns/cp1-default.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Classical Pattern #1 - The Default Pattern (a pattern that should be generally avoided)
			 Description: create an object using the Parent() constructor and assign this object to the Child()'s prototype
			 */

			function inherit(C, P) {
				C.prototype = new P();
			}

			// the parent constructor
			function Parent(name) {
				this.name = name || 'Adam';
			}
			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};
			// empty child constructor
			function Child(name) {
			}

			// inheritance magic happens here
			inherit(Child, Parent);

			var kid = new Child();
			console.log(kid.say()); // "Adam"

			// Drawback 1: own properties added to `this` is inherited
			var kiddo = new Child();
			kiddo.name = "Patrick";
			console.log(kiddo.say()); // "Patrick"


			// Drawback 2: it doesn't enable you to pass parameters to the child constructor
			var s = new Child('Seth');
			console.log(s.say()); // "Adam"


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/cp2-rent-a-constructor.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Classical Pattern #2 - Rent a Constructor (a pattern that should be generally avoided)
			 Description: it borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments
			 */

			// the parent constructor
			function Parent(name) {
				this.name = name || 'Adam';
			}

			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};

			// child constructor
			function Child(name) {
				Parent.apply(this, arguments);
			}

			var kid = new Child("Patrick");
			console.log(kid.name); // "Patrick"

			// Drawback 1: nothing from the prototype gets inherited
			console.log(typeof kid.say); // "undefined"

			// Multiple Inheritance by Borrowing Constructors
			function Cat() {
				this.legs = 4;
				this.say = function () {
					return "meaowww";
				}
			}

			function Bird() {
				this.wings = 2;
				this.fly = true;
			}

			function CatWings() {
				Cat.apply(this);
				Bird.apply(this);
			}

			var jane = new CatWings();
			console.dir(jane);


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/cp3-rent-and-set-prototype.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Classical Pattern #3 - Rent and Set Prototype (a pattern that should be generally avoided)
			 Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
			 */

			// the parent constructor
			function Parent(name) {
				this.name = name || 'Adam';
			}

			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};

			// child constructor
			function Child(name) {
				Parent.apply(this, arguments);
			}

			Child.prototype = new Parent();

			var kid = new Child("Patrick");
			console.log(kid.name); // "Patrick"
			console.log(typeof kid.say); // function
			console.log(kid.say()); // Patrick
			console.dir(kid);
			delete kid.name;
			console.log(kid.say()); // "Adam"

			// Drawback - the parent constructor is called twice, so it could be inefficient


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/cp4-share-the-prototype.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Classical Pattern #3 - Share the Prototype (a pattern that should be generally avoided)
			 Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
			 */

			function inherit(C, P) {
				C.prototype = P.prototype;
			}

			// the parent constructor
			function Parent(name) {
				this.name = name || 'Adam';
			}

			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};

			// child constructor
			function Child(name) {
			}

			inherit(Child, Parent);

			var kid = new Child('Patrick');
			console.log(kid.name); // undefined
			console.log(typeof kid.say); // function
			kid.name = 'Patrick';
			console.log(kid.say()); // Patrick
			console.dir(kid);


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/cp5-a-temporary-constructor.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Classical Pattern #5 - A Temporary Constructor (a pattern that should be generally avoided)
			 Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
			 */

			/* Basic */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 }*/

			/* Storing the Superclass */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 C.uber = P.prototype;
			 }*/

			/* Resetting the Constructor Pointer */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 C.uber = P.prototype;
			 C.prototype.constructor = C;
			 }*/

			/* in closure */
			var inherit = (function () {
				var F = function () {
				};
				return function (C, P) {
					F.prototype = P.prototype;
					C.prototype = new F();
					C.uber = P.prototype;
					C.prototype.constructor = C;
				}
			}());

			function Parent(name) {
				this.name = name || 'Adam';
			}

			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};

			// child constructor
			function Child(name) {
			}

			inherit(Child, Parent);

			var kid = new Child();
			console.log(kid.name); // undefined
			console.log(typeof kid.say); // function
			kid.name = 'Patrick';
			console.log(kid.say()); // Patrick
			console.log(kid.constructor.name); // Child
			console.log(kid.constructor === Parent); // false


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/inheritance-by-copying-properties.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Inheritance by Copying Properties
			 Description: an object gets functionality from another object, simply by copying it
			 */

			/* shallow copy */
			function extend(parent, child) {
				var i;
				child = child || {};
				for (i in parent) {
					if (parent.hasOwnProperty(i)) {
						child[i] = parent[i];
					}
				}
				return child;
			}

			var dad = {name:"Adam"};
			var kid = extend(dad);
			console.log(kid.name); // "Adam"

			var dad = {
				counts:[1, 2, 3],
				reads:{paper:true}
			};
			var kid = extend(dad);
			kid.counts.push(4);
			console.log(dad.counts.toString()); // "1,2,3,4"
			console.log(dad.reads === kid.reads); // true


			/* deep copy */
			function extendDeep(parent, child) {
				var i,
						toStr = Object.prototype.toString,
						astr = "[object Array]";

				child = child || {};

				for (i in parent) {
					if (parent.hasOwnProperty(i)) {
						if (typeof parent[i] === 'object') {
							child[i] = (toStr.call(parent[i]) === astr) ? [] : {};
							extendDeep(parent[i], child[i]);
						} else {
							child[i] = parent[i];
						}
					}
				}
				return child;
			}

			var dad = {
				counts:[1, 2, 3],
				reads:{paper:true}
			};
			var kid = extendDeep(dad);

			kid.counts.push(4);
			console.log(kid.counts.toString()); // "1,2,3,4"
			console.log(dad.counts.toString()); // "1,2,3"

			console.log(dad.reads === kid.reads); // false
			kid.reads.paper = false;


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/klass.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Klass (a pattern that should be generally avoided)
			 Description: generally a pattern that should be avoided unless one is more comfortable with class than prototype
			 */

			// Drawback: it brings the whole confusing notion of classes, which don’t technically exist in the language

			// Benefit: you can tweak the syntax and the conventions to resemble another of your favorite languages

			var klass = function (Parent, props) {

				var Child, F, i;

				// 1.
				// new constructor
				Child = function () {
					if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
						Child.uber.__construct.apply(this, arguments);
					}
					if (Child.prototype.hasOwnProperty("__construct")) {
						Child.prototype.__construct.apply(this, arguments);
					}
				};

				// 2.
				// inherit
				Parent = Parent || Object;
				F = function () {
				};
				F.prototype = Parent.prototype;
				Child.prototype = new F();
				Child.uber = Parent.prototype;
				Child.prototype.constructor = Child;

				// 3.
				// add implementation methods
				for (i in props) {
					if (props.hasOwnProperty(i)) {
						Child.prototype[i] = props[i];
					}
				}

				// return the "class"
				return Child;
			};

			var Man = klass(null, {
				__construct:function (what) {
					console.log("Man's constructor");
					this.name = what;
				},
				getName:function () {
					return this.name;
				}
			});

			var first = new Man('Adam'); // logs "Man's constructor"
			first.getName(); // "Adam"

			var SuperMan = klass(Man, {
				__construct:function (what) {
					console.log("SuperMan's constructor");
				},
				getName:function () {
					var name = SuperMan.uber.getName.call(this);
					return "I am " + name;
				}
			});

			var clark = new SuperMan('Clark Kent');
			clark.getName(); // "I am Clark Kent"

			console.log(clark instanceof Man); // true
			console.log(clark instanceof SuperMan); // true

			/* Title: Classical Pattern #5 - A Temporary Constructor (a pattern that should be generally avoided)
			 Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
			 */

			/* Basic */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 }*/

			/* Storing the Superclass */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 C.uber = P.prototype;
			 }*/

			/* Resetting the Constructor Pointer */
			/*function inherit(C, P) {
			 var F = function () {};
			 F.prototype = P.prototype;
			 C.prototype = new F();
			 C.uber = P.prototype;
			 C.prototype.constructor = C;
			 }*/

			/* in closure */
			var inherit = (function () {
				var F = function () {
				};
				return function (C, P) {
					F.prototype = P.prototype;
					C.prototype = new F();
					C.uber = P.prototype;
					C.prototype.constructor = C;
				}
			}());

			function Parent(name) {
				this.name = name || 'Adam';
			}

			// adding functionality to the prototype
			Parent.prototype.say = function () {
				return this.name;
			};

			// child constructor
			function Child(name) {
			}

			inherit(Child, Parent);

			var kid = new Child();
			console.log(kid.name); // undefined
			console.log(typeof kid.say); // function
			kid.name = 'Patrick';
			console.log(kid.say()); // Patrick
			console.log(kid.constructor.name); // Child
			console.log(kid.constructor === Parent); // false


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>


================================================
FILE: code-reuse-patterns/mix-ins.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Mix-ins
			 Description: copy from any number of objects and mix them all into a new object
			 */

			function mix() {
				var arg, prop, child = {};
				for (arg = 0; arg < arguments.length; arg += 1) {
					for (prop in arguments[arg]) {
						if (arguments[arg].hasOwnProperty(prop)) {
							child[prop] = arguments[arg][prop];
						}
					}
				}
				return child;
			}

			var cake = mix(
					{eggs:2, large:true},
					{butter:1, salted:true},
					{flour:'3 cups'},
					{sugar:'sure!'}
			);

			console.dir(cake);


			// reference
			// http://addyosmani.com/resources/essentialjsdesignpatterns/book/#mixinpatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: code-reuse-patterns/prototypal-inheritance.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Prototypal Inheritance
			 Description: objects inherit from other objects
			 */

			function object(o) {
				function F() {
				}

				F.prototype = o;
				return new F();
			}

			// object to inherit from
			var parent = {
				name:"Papa"
			};

			// the new object
			var child = object(parent);

			// testing
			console.log(child.name); // "Papa"


			// parent constructor
			function Person() {
				// an "own" property
				this.name = "Adam";
			}
			// a property added to the prototype
			Person.prototype.getName = function () {
				return this.name;
			};

			// create a new person
			var papa = new Person();

			// inherit
			var kid = object(papa);

			// test that both the own property
			// and the prototype property were inherited
			console.log(kid.getName()); // "Adam"

			// parent constructor
			function Person() {
				// an "own" property
				this.name = "Adam";
			}

			// a property added to the prototype
			Person.prototype.getName = function () {
				return this.name;
			};

			// inherit
			var kid = object(Person.prototype);
			console.log(typeof kid.getName); // "function", because it was in the prototype
			console.log(typeof kid.name); // "undefined", because only the prototype was inherited

			/* Addition to ECMAScript 5 */
			var child = Object.create(parent);

			var child = Object.create(parent, {
				age:{ value:2 } // ECMA5 descriptor
			});
			console.log(child.hasOwnProperty("age")); // true


			// reference
			// http://shop.oreilly.com/product/9780596806767.do
		</script>
	</body>
</html>

================================================
FILE: css/style.css
================================================
/*
 * HTML5 ✰ Boilerplate
 *
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 *
 * Detailed information about this CSS: h5bp.com/css
 *
 * ==|== normalize ==========================================================
 */


/* =============================================================================
   HTML5 display definitions
   ========================================================================== */

article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; }
audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; }
audio:not([controls]) { display: none; }
[hidden] { display: none; }


/* =============================================================================
   Base
   ========================================================================== */

/*
 * 1. Correct text resizing oddly in IE6/7 when body font-size is set using em units
 * 2. Force vertical scrollbar in non-IE
 * 3. Prevent iOS text size adjust on device orientation change, without disabling user zoom: h5bp.com/g
 */

html { font-size: 100%; overflow-y: scroll; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }

body { margin: 0; font-size: 1em; line-height: 1.4; }

body, button, input, select, textarea { font-family: sans-serif; color: #222; }

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection declarations have to be separate
 * Also: hot pink! (or customize the background color to match your design)
 */

::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }


/* =============================================================================
   Links
   ========================================================================== */

a { color: #06e; }
a:visited { color: #06e; }
a:hover { color: #06e; }
a:focus { outline: thin dotted; }

/* Improve readability when focused and hovered in all browsers: h5bp.com/h */
a:hover, a:active { outline: 0; }


/* =============================================================================
   Typography
   ========================================================================== */

abbr[title] { border-bottom: 1px dotted; }

b, strong { font-weight: bold; }

blockquote { margin: 1em 40px; }

dfn { font-style: italic; }

hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }

ins { background: #ff9; color: #000; text-decoration: none; }

mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; }

/* Redeclare monospace font family: h5bp.com/j */
pre, code, kbd, samp { font-family: monospace, serif; _font-family: 'courier new', monospace; font-size: 1em; }

/* Improve readability of pre-formatted text in all browsers */
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; }

q { quotes: none; }
q:before, q:after { content: ""; content: none; }

small { font-size: 85%; }

/* Position subscript and superscript content without affecting line-height: h5bp.com/k */
sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }


/* =============================================================================
   Lists
   ========================================================================== */

ul, ol { margin: 1em 0; padding: 0 0 0 40px; }
dd { margin: 0 0 0 40px; }
nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; }


/* =============================================================================
   Embedded content
   ========================================================================== */

/*
 * 1. Improve image quality when scaled in IE7: h5bp.com/d
 * 2. Remove the gap between images and borders on image containers: h5bp.com/e
 */

img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; }

/*
 * Correct overflow not hidden in IE9
 */

svg:not(:root) { overflow: hidden; }


/* =============================================================================
   Figures
   ========================================================================== */

figure { margin: 0; }


/* =============================================================================
   Forms
   ========================================================================== */

form { margin: 0; }
fieldset { border: 0; margin: 0; padding: 0; }

/* Indicate that 'label' will shift focus to the associated form element */
label { cursor: pointer; }

/*
 * 1. Correct color not inheriting in IE6/7/8/9
 * 2. Correct alignment displayed oddly in IE6/7
 */

legend { border: 0; *margin-left: -7px; padding: 0; }

/*
 * 1. Correct font-size not inheriting in all browsers
 * 2. Remove margins in FF3/4 S5 Chrome
 * 3. Define consistent vertical alignment display in all browsers
 */

button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; }

/*
 * 1. Define line-height as normal to match FF3/4 (set using !important in the UA stylesheet)
 */

button, input { line-height: normal; }

/*
 * 1. Display hand cursor for clickable form elements
 * 2. Allow styling of clickable form elements in iOS
 * 3. Correct inner spacing displayed oddly in IE7 (doesn't effect IE6)
 */

button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; *overflow: visible; }

/*
 * Consistent box sizing and appearance
 */

input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; }
input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; }
input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; }

/*
 * Remove inner padding and border in FF3/4: h5bp.com/l
 */

button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; }

/*
 * 1. Remove default vertical scrollbar in IE6/7/8/9
 * 2. Allow only vertical resizing
 */

textarea { overflow: auto; vertical-align: top; resize: vertical; }

/* Colors for form validity */
input:valid, textarea:valid {  }
input:invalid, textarea:invalid { background-color: #f0dddd; }


/* =============================================================================
   Tables
   ========================================================================== */

table { border-collapse: collapse; border-spacing: 0; }
td { vertical-align: top; }


/* ==|== primary styles =====================================================
   Author: Shi Chuan
   ========================================================================== */

.fork img {
    position: absolute;
    top: 0;
    right: 0;
}

html {
  background:#F8FAF0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 100%;
}

body {
  margin:0 auto;
  padding: 1em;
  word-wrap: break-word;
  word-break: break-word;
}

header {
  position: relative;
  margin-top: 2em;
  margin-bottom: 1em;
}

header img {padding-top:5px; border-top:1px solid #ccc; display:block;}

h1, h2, h3 {font-family: 'Tinos', serif; padding:0; margin:0;}

h1 {
  font-size: 1.6em;
  float:left; 
  margin-top:7px;
}
#btns {float:right; margin-bottom:10px;}

#btns span {display:block; float:left;}
.st_sharethis {margin-top:2px;}
h2 {
  font-size: 1.4em;
  display:block;
  padding-bottom:0.5em;
  border-bottom:1px solid #ccc;
  margin-bottom:1em;
  margin-top:1.5em;
}
h3 {
  font-size: 1.2em;
  color:#555;
}
a {
  text-decoration:none;
  
}

ul, ul li {
  list-style:none; margin-left:0; padding-left:10px; color:#444;
}

ul { 
  margin-bottom:1em;
}

li {
  margin-bottom:0.5em;
}

iframe,
object,
embed,
img {
  max-width: 100%;
}

nav {
  text-align: left;
  background: #324A69;
  background: -o-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -webkit-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -moz-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -ms-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  margin: 1em 0;
}

nav li {
  color: #fff;
  list-style-position: inside;
  list-style-type: disc;
  border-bottom: solid 1px rgba(255, 255, 255, 0.2);
  margin: 0;
}

nav li a:visited,
nav li a {
  color: #fff;
}
nav li a {
  font-size: 0.9em;
  display: block;
  padding: 0.5em 0.3em;
}

nav li a:hover {
  color: #ccc;
}

nav #toggle-nav {
  background: none;
  background: #546377;
  /*background: -o-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -webkit-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -moz-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));
  background: -ms-linear-gradient(rgba(50, 74, 105, 0.8), rgba(50, 74, 105, 1));*/
  border: none;
  color: #fff;
  left: 0;
  height: 40px;
  position: absolute;
  bottom: 100%;
  width: 70px;
}

nav #toggle-nav:hover {
  background: #2A3B50;
  /*background: -webkit-linear-gradient(rgba(69, 105, 151, 0.8), rgba(50, 74, 105, 1));
  background: -moz-linear-gradient(rgba(69, 105, 151, 0.8), rgba(50, 74, 105, 1));
  background: -ms-linear-gradient(rgba(69, 105, 151, 0.8), rgba(50, 74, 105, 1));*/
}

nav #toggle-nav:active {
  background: #2A3B50;
}

footer {
  text-align:center;
  margin-top:2em;
  margin-bottom:1em;
}



/* ==|== media queries ======================================================
   PLACEHOLDER Media Queries for Responsive Design.
   These override the primary ('mobile first') styles
   Modify as content requires.
   ========================================================================== */
@media only screen and (min-width: 48em) {
  body {
    max-width: 66%;
  }

  .sticky {
    position: fixed;
    margin: 0;
    left: 0;
    top: 3em;
    width: 16%;
    z-index: 2;
  }

  nav.sty {
    width: 16%;
  }
}


/* ==|== non-semantic helper classes ========================================
   Please define your styles before this section.
   ========================================================================== */

/* For image replacement */
.ir { display: block; border: 0; text-indent: -999em; overflow: hidden; background-color: transparent; background-repeat: no-repeat; text-align: left; direction: ltr; *line-height: 0; }
.ir br { display: none; }

/* Hide from both screenreaders and browsers: h5bp.com/u */
.hidden { display: none !important; visibility: hidden; }

/* Hide only visually, but have it available for screenreaders: h5bp.com/v */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }

/* Extends the .visuallyhidden class to allow the element to be focusable when navigated to via the keyboard: h5bp.com/p */
.visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; }

/* Hide visually and from screenreaders, but maintain layout */
.invisible { visibility: hidden; }

/* Contain floats: h5bp.com/q */
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }

/*@media screen and (min-width: 20em){
  body {}
}*/

/* ==|== print styles =======================================================
   Print styles.
   Inlined to avoid required HTTP connection: h5bp.com/r
   ========================================================================== */

@media print {
  * { background: transparent !important; color: black !important; box-shadow:none !important; text-shadow: none !important; filter:none !important; -ms-filter: none !important; } /* Black prints faster: h5bp.com/s */
  a, a:visited { text-decoration: underline; }
  a[href]:after { content: " (" attr(href) ")"; }
  abbr[title]:after { content: " (" attr(title) ")"; }
  .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }  /* Don't show links for images, or javascript/internal links */
  pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
  thead { display: table-header-group; } /* h5bp.com/t */
  tr, img { page-break-inside: avoid; }
  img { max-width: 100% !important; }
  @page { margin: 0.5cm; }
  p, h2, h3 { orphans: 3; widows: 3; }
  h2, h3 { page-break-after: avoid; }
}

================================================
FILE: design-patterns/builder.html
================================================
<!doctype html>
<html lang="en">
  <head>
    <title>JavaScript Patterns</title>
    <meta charset="utf-8">
  </head>
  <body>
    <button id="test">Test</button>
    <script>
      /* Title: Builder
       Description: constructs complex objects by separating construction and representation
       */
      function getBeerById(id, callback) {
        // Make request for beer by ID, then return the beer data.
        asyncRequest('GET', 'beer.uri?id=' + id, function (resp) {
          // callback response
          callback(resp.responseText);
        });
      }
      var el = document.querySelector('#test');
      el.addEventListener('click', getBeerByIdBridge, false);
      function getBeerByIdBridge(e) {
        getBeerById(this.id, function (beer) {
          console.log('Requested Beer: ' + beer);
        });
      }
      // reference
      // http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#builderpatternjquery
    </script>
  </body>
</html>


================================================
FILE: design-patterns/chain-of-responsibility.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Chain of responsibility
			 Description: delegates commands to a chain of processing objects
			 */

			var NO_TOPIC = -1;
			var Topic;

			function Handler(s, t) {
				this.successor = s || null;
				this.topic = t || 0;
			}

			Handler.prototype = {
				handle:function () {
					console.log(this.has());
					if (this.successor) {
						this.successor.handle();
					}
					console.log(this.topic);
				},
				has:function () {
					return this.topic != NO_TOPIC;
				}
			};

			var _handle = Handler.prototype.handle;

			var app = new Handler({
				handle:function () {
					console.log('app handle');
				}
			}, 3);

			var dialog = new Handler(app, 1);
			//dialog.handle = function () {
			//if (this.has()) {
			//} else {
			//console.log('dialog handle');
			//_handle.call(this);
			//}
			//}

			var button = new Handler(dialog, 2);
			//button.handle = function () {
			//if (this.has()) {
			//} else {
			//console.log('dialog handle');
			//_handle.call(this);
			//}
			//}

			button.handle();

			// reference
			// https://gist.github.com/1174982
		</script>
	</body>
</html>

================================================
FILE: design-patterns/command.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Command
			 Description: creates objects which encapsulate actions and parameters
			 */

			(function () {

				var CarManager = {

					/* request information */
					requestInfo:function (model, id) {
						return 'The purchase info for ' + model + ' with ID ' + id + ' is being processed...';
					},

					/* purchase the car */
					buyVehicle:function (model, id) {
						return 'You have successfully purchased Item ' + id + ', a ' + model + '.';
					}

				};

				CarManager.execute = function (commad) {
					return CarManager[commad.request](commad.model, commad.carID);
				};

				var actionA = CarManager.execute({request:'requestInfo', model:'Ford Mondeo', carID:'543434'});
				console.log(actionA);
				var actionB = CarManager.execute({request:'buyVehicle', model:'Ford Mondeo', carID:'543434'});
				console.log(actionB);

			})();

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#commandpatternjavascript
		</script>
	</body>
</html>

================================================
FILE: design-patterns/decorator.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Decorator
			 Description: dynamically adds/overrides behaviour in an existing method of an object
			 */

			var tree = {};
			tree.decorate = function () {
				console.log('Make sure the tree won\'t fall');
			};

			tree.getDecorator = function (deco) {
				tree[deco].prototype = this;
				return new tree[deco];
			};

			tree.RedBalls = function () {
				this.decorate = function () {
					this.RedBalls.prototype.decorate();
					console.log('Put on some red balls');
				}
			};

			tree.BlueBalls = function () {
				this.decorate = function () {
					this.BlueBalls.prototype.decorate();
					console.log('Add blue balls');
				}
			};

			tree.Angel = function () {
				this.decorate = function () {
					this.Angel.prototype.decorate();
					console.log('An angel on the top');
				}
			};

			tree = tree.getDecorator('BlueBalls');
			tree = tree.getDecorator('Angel');
			tree = tree.getDecorator('RedBalls');

			tree.decorate();

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#decoratorpatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: design-patterns/facade.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Facade
			 Description: provides a simplified interface to a large body of code
			 */

			var mobileEvent = {
				// ...
				stop:function (e) {
					e.preventDefault();
					e.stopPropagation();
				}
				// ...
			};

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#facadepatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: design-patterns/factory.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Factory method
			 Description: creates objects without specifying the exact class to create
			 */

			var jsp = {};
			jsp.dom = {};
			jsp.dom.Text = function () {
				this.insert = function (where) {
					var txt = document.createTextNode(this.url);
					where.appendChild(txt);
				};
			};
			jsp.dom.Link = function () {
				this.insert = function (where) {
					var link = document.createElement('a');
					link.href = this.url;
					link.appendChild(document.createTextNode(this.url));
					where.appendChild(link);
				};
			};
			jsp.dom.Image = function () {
				this.insert = function (where) {
					var im = document.createElement('img');
					im.src = this.url;
					where.appendChild(im);
				};
			};
			jsp.dom.factory = function (type) {
				return new jsp.dom[type];
			}

			var o = jsp.dom.factory('Link');
			o.url = 'http://google.com';
			o.insert(document.body);

			var taskManager = {};

			taskManager.update = function () {
				console.log('update');
			}

			taskManager.read = function () {
				console.log('read');
			}

			var type = 'update';
			var task;

			if (type === 'update') {
				task = new taskManager.update();
			}

			if (type === 'read') {
				task = new taskManager.read();
			}

			taskManager.factory = function (typeType) {
				return new taskManager[typeType];
			}

			task = new taskManager[type];

			/*** Built-in Object Factory ***/
			var o = new Object(),
					n = new Object(1),
					s = Object('1'),
					b = Object(true);

			// test
			o.constructor === Object;  // true
			n.constructor === Number;  // true
			s.constructor === String;  // true
			b.constructor === Boolean; // true

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: design-patterns/iterator.html
================================================
<!doctype html>
<html lang="en">
  <head>
    <title>JavaScript Patterns</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script>
      /* Title: Iterator
       Description: implements a specialized language
       */
      var element;
      while (element - agg.next()) {
        // do something with the element
        console.log(element);
      }
      while (agg.hasNext()) {
        // do something with the next element...
        console.log(agg.next());
      }
      var agg = (function () {
        var index = 0,
            data = [1, 2, 3, 4, 5],
            length = data.length;
        return {
          next:function () {
            var element;
            if (!this.hasNext()) {
              return null;
            }
            element = data[index];
            index = index + 2;
            return element;
          },
          hasNext:function () {
            return index < length;
          },
          rewind:function () {
            index = 0;
          },
          current:function () {
            return data[index];
          }
        };
      }());
      // this loop logs 1, then 3, then 5
      while (agg.hasNext()) {
        console.log(agg.next());
      }
      // go back
      agg.rewind();
      console.log(agg.current()); // 1
      // reference
      // http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#iteratorpatternjquery
      // http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
    </script>
  </body>
</html>

================================================
FILE: design-patterns/mediator.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Mediator
			 Description: allows loose coupling between classes by being the only class that has detailed knowledge of their methods
			 */

			function Player(name) {
				this.points = 0;
				this.name = name;
			}
			Player.prototype.play = function () {
				this.points += 1;
				mediator.played();
			};
			var scoreboard = {

				// HTML element to be updated
				element:document.getElementById('results'),

				// update the score display
				update:function (score) {
					var i, msg = '';
					for (i in score) {
						if (score.hasOwnProperty(i)) {
							msg += '<p><strong>' + i + '<\/strong>: ';
							msg += score[i];
							msg += '<\/p>';
						}
					}
					this.element.innerHTML = msg;
				}
			};

			var mediator = {

				// all the player
				players:{},

				// initialization
				setup:function () {
					var players = this.players;
					players.home = new Player('Home');
					players.guest = new Player('Guest');
				},

				// someone plays, update the score
				played:function () {
					var players = this.players,
							score = {
								Home:players.home.points,
								Guest:players.guest.points
							};

					scoreboard.update(score);
				},

				// handle user interactions
				keypress:function (e) {
					e = e || window.event; // IE
					if (e.which === 49) { // key "1"
						mediator.players.home.play();
						return;
					}
					if (e.which === 48) { // key "0"
						mediator.players.guest.play();
						return;
					}
				}
			};

			// go!
			mediator.setup();
			window.onkeypress = mediator.keypress;

			// game over in 30 seconds
			setTimeout(function () {
				window.onkeypress = null;
				console.log('Game over!');
			}, 30000);

			// reference
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: design-patterns/multiton.html
================================================
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Multiton / Object Pool
 Description: stores references to each object created for a class
*/


//example class
function Widget() {
  // cache
  Widget.instances = Widget.instances || [];
 
  // provide metadata
  this.id = Widget.length;
  
  // store reference
  Widget.instances.push(this);
  // implicit return:
  // return this;
}

//getInstance method
Widget.getInstance = function (index) {
    return Widget.instances[index];
};


new Widget();
new Widget();
Widget.instances.length === 2; //true
Widget.instances[0].id === 1; //true
Widget.instances[1] === Widget.getInstance(1); //true

//Another example class uses the id to ensure prior
//instances with the same id are removed from the object pool
(function (global) {
    var index = -1;
    
    function Widget(id) {
        // provide metadata
        //accept the id parameter to allow overwriting
        this.id = id || (index += 1);
      
        // store reference
        Widget.instances[this.id] = this;
        // implicit return:
        // return this;
    }
    
    //cache
    Widget.instances = {};
    
    //getInstance method
    Widget.getInstance = function (index) {
        return Widget.instances[index];
    };
    
    return global.Widget = Widget;
}(this));

new Widget();
Widget.getInstance(0).id = 0; //true

var orig = new Widget();
var compare = new Widget(1);
compare.id === 1; //true
compare === orig; //false

new Widget("test");
Widget.instances.test === Widget.getInstance("test"); //true

//passing the id as a parameter does not increment the index
new Widget().id === 2; //true


//general reference about the multiton pattern: http://en.wikipedia.org/wiki/Multiton_pattern
</script>
</body>
</html>

================================================
FILE: design-patterns/observer.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Observer
			 Description: is a publish/subscribe pattern which allows a number of observer objects to see an event
			 */

			var observer = {
				addSubscriber:function (callback) {
					this.subscribers[this.subscribers.length] = callback;
				},
				removeSubscriber:function (callback) {
					for (var i = 0; i < this.subscribers.length; i++) {
						if (this.subscribers[i] === callback) {
							delete(this.subscribers[i]);
						}
					}
				},
				publish:function (what) {
					for (var i = 0; i < this.subscribers.length; i++) {
						if (typeof this.subscribers[i] === 'function') {
							this.subscribers[i](what);
						}
					}
				},
				make:function (o) { // turns an object into a publisher
					for (var i in this) {
						o[i] = this[i];
						o.subscribers = [];
					}
				}
			};

			var blogger = {
				writeBlogPost:function () {
					var content = 'Today is ' + new Date();
					this.publish(content);
				}
			};

			var la_times = {
				newIssue:function () {
					var paper = 'Martians have landed on Earth!';
					this.publish(paper);
				}
			};

			observer.make(blogger);
			observer.make(la_times);

			var jack = {
				read:function (what) {
					console.log('I just read that ' + what)
				}
			};

			var jill = {
				gossip:function (what) {
					console.log('You didn\'t hear it from me, but ' + what)
				}
			};

			blogger.addSubscriber(jack.read);
			blogger.addSubscriber(jill.gossip);
			blogger.writeBlogPost();

			blogger.removeSubscriber(jill.gossip);
			blogger.writeBlogPost();

			la_times.addSubscriber(jill.gossip);
			la_times.newIssue();

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: design-patterns/proxy.html
================================================
<!doctype html>
<html lang="en">
<head>
	<title>JavaScript Patterns</title>
	<meta charset="utf-8">
	<style>
		img {
			float: left;
			padding-right: 7px;
		}

		div {
			padding: 7px;
			border: 1px solid #ccc;
			background: #eee;
			width: 400px;
		}

		h2 {
			margin: 0;
		}

		span {
			text-decoration: underline;
			cursor: pointer;
		}

		body {
			padding: 21px;
			font-size: 105%;
			font-family: Helvetica;
		}

		input {
			margin-right: 7px;
		}

		a {
			color: blue;
		}
	</style>
</head>
<body>
	<h1>Dave Matthews vids</h1>
	<p><span id="toggle-all">Toggle Checked</span></p>
	<ol id="vids">
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2158073">Gravedigger</a></li>
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--4472739">Save Me</a></li>
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--45286339">Crush</a></li>
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2144530">Don't Drink The
			Water</a></li>
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--217241800">Funny the Way It
			Is</a></li>
		<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2144532">What Would You Say</a>
		</li>
	</ol>

	<script>
		/* Title: Proxy
		 Description: provides a placeholder for another object to control access, reduce cost, and reduce complexity
		 */

		var $ = function (id) {
			return document.getElementById(id);
		};

		var http = {
			makeRequest:function (ids, callback) {
				var url = 'http://query.yahooapis.com/v1/public/yql?q=',
						sql = 'select * from music.video.id where ids IN ("%ID%")',
						format = "format=json",
						handler = "callback=" + callback,
						script = document.createElement('script');

				sql = sql.replace('%ID%', ids.join('","'));
				sql = encodeURIComponent(sql);

				url += sql + '&' + format + '&' + handler;
				script.src = url;

				document.body.appendChild(script);
			}
		};

		var proxy = {
			ids:[],
			delay:50,
			timeout:null,
			callback:null,
			context:null,
			makeRequest:function (id, callback, context) {

				// add to the queue
				this.ids.push(id);

				this.callback = callback;
				this.context = context;

				// set up timeout
				if (!this.timeout) {
					this.timeout = setTimeout(function () {
						proxy.flush();
					}, this.delay);
				}
			},
			flush:function () {
				http.makeRequest(this.ids, 'proxy.handler');
				// clear timeout and queue
				this.timeout = null;
				this.ids = [];

			},
			handler:function (data) {
				var i, max;

				// single video
				if (parseInt(data.query.count, 10) === 1) {
					proxy.callback.call(proxy.context, data.query.results.Video);
					return;
				}

				// multiple videos
				for (i = 0, max = data.query.results.Video.length; i < max; i += 1) {
					proxy.callback.call(proxy.context, data.query.results.Video[i]);
				}
			}
		};


		var videos = {
			getPlayer:function (id) {
				return '' +
						'<object width="400" height="255" id="uvp_fop" allowFullScreen="true">' +
						'<param name="movie" value="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf"\/>' +
						'<param name="flashVars" value="id=v' + id + '&amp;eID=1301797&amp;lang=us&amp;enableFullScreen=0&amp;shareEnable=1"\/>' +
						'<param name="wmode" value="transparent"\/>' +
						'<embed ' +
						'height="255" ' +
						'width="400" ' +
						'id="uvp_fop" ' +
						'allowFullScreen="true" ' +
						'src="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf" ' +
						'type="application/x-shockwave-flash" ' +
						'flashvars="id=v' + id + '&amp;eID=1301797&amp;lang=us&amp;ympsc=4195329&amp;enableFullScreen=1&amp;shareEnable=1"' +
						'\/>' +
						'<\/object>';
			},

			updateList:function (data) {
				var id,
						html = '',
						info;

				if (data.query) {
					data = data.query.results.Video;
				}
				id = data.id;
				html += '<img src="' + data.Image[0].url + '" width="50" \/>';
				html += '<h2>' + data.title + '<\/h2>';
				html += '<p>' + data.copyrightYear + ', ' + data.label + '<\/p>';
				if (data.Album) {
					html += '<p>Album: ' + data.Album.Release.title + ', ' + data.Album.Release.releaseYear + '<br \/>';
				}
				html += '<p><a class="play" href="http://new.music.yahoo.com/videos/--' + id + '">&raquo; play<\/a><\/p>';
				info = document.createElement('div');
				info.id = "info" + id;
				info.innerHTML = html;
				$('v' + id).appendChild(info);
			},

			getInfo:function (id) {
				var info = $('info' + id);

				if (!info) {
					proxy.makeRequest(id, videos.updateList, videos);
					return;
				}

				if (info.style.display === "none") {
					info.style.display = '';
				} else {
					info.style.display = 'none';
				}
			}
		};


		$('vids').onclick = function (e) {
			var src, id;

			e = e || window.event;
			src = e.target || e.srcElement;

			if (src.nodeName.toUpperCase() !== "A") {
				return;
			}

			if (typeof e.preventDefault === "function") {
				e.preventDefault();
			}
			e.returnValue = false;

			id = src.href.split('--')[1];

			if (src.className === "play") {
				src.parentNode.innerHTML = videos.getPlayer(id);
				return;
			}

			src.parentNode.id = "v" + id;
			videos.getInfo(id);
		};

		$('toggle-all').onclick = function (e) {

			var hrefs,
					i,
					max,
					id;

			hrefs = $('vids').getElementsByTagName('a');
			for (i = 0, max = hrefs.length; i < max; i += 1) {
				// skip play links
				if (hrefs[i].className === "play") {
					continue;
				}
				// skip unchecked
				if (!hrefs[i].parentNode.firstChild.checked) {
					continue;
				}

				id = hrefs[i].href.split('--')[1];
				hrefs[i].parentNode.id = "v" + id;
				videos.getInfo(id);
			}
		};

		// reference
		// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#proxypatternjquery
		// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
	</script>
</body>
</html>

================================================
FILE: design-patterns/singleton.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Singleton
			 Description: restricts object creation for a class to only one instance
			 */

			var obj = {
				myprop:'my value'
			};

			var obj2 = {
				myprop:'my value'
			};
			obj === obj2; // false
			obj == obj2;  // false

			var uni = new Universe();
			var uni2 = new Universe();
			uni === uni2; // true

			function Universe() {

				// do we have an existing instance?
				if (typeof Universe.instance === 'object') {
					return Universe.instance;
				}

				// proceed as normal
				this.start_time = 0;
				this.bang = "Big";

				// cache
				Universe.instance = this;

				// implicit return:
				// return this;
			}

			// testing
			var uni = new Universe();
			var uni2 = new Universe();
			uni === uni2; // true

			/*** Instance in a Closure ***/

			function Universe() {

				// the cached instance
				var instance = this;

				// proceed as normal
				this.start_time = 0;
				this.bang = "Big";

				// rewrite the contructor
				Universe = function () {
					return instance;
				};
			}

			function Universe() {

				// the cached instance
				var instance;

				// rewrite the constructor
				Universe = function Universe() {
					return instance;
				};

				// carry over the prototype properties
				Universe.prototype = this;

				// the instance
				instance = new Universe();

				// reset the constructor pointer
				instance.constructor = Universe;

				// all the functionality
				instance.start_time = 0;
				instance.bang = "Big";

				return instance;
			}


			// testing
			var uni = new Universe();
			var uni2 = new Universe();
			uni === uni2; // true

			// adding to the prototype
			Universe.prototype.nothing = true;

			var uni = new Universe();

			// again adding to the prototype
			// after the initial object is created
			Universe.prototype.everything = true;

			var uni2 = new Universe();

			// only the original prototype was
			// linked to the objects
			uni.nothing; // true
			uni2.nothing; // true
			uni.everything; // true
			uni2.everything; // true

			// that sounds right:
			uni.constructor.name; // "Universe"
			uni.constructor === Universe; // true

			var Universe;

			(function () {

				var instance;

				Universe = function Universe() {

					if (instance) {
						return instance;
					}

					instance = this;

					// all the functionality
					this.start_time = 0;
					this.bang = "Big";
				};
			}());

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>


================================================
FILE: design-patterns/strategy.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Strategy
			 Description: allows one of a family of algorithms to be selected on-the-fly at runtime
			 */

			var validator = {

				// all available checks
				types:{},

				// error messages in the current
				// validation session
				messages:[],

				// current validation config
				// name: validation type
				config:{},

				// the interface method
				// 'data' is key => value pairs
				validate:function (data) {

					var i, msg, type, checker, result_ok;

					// reset all messages
					this.messages = [];

					for (i in data) {

						if (data.hasOwnProperty(i)) {

							type = this.config[i];
							checker = this.types[type];

							if (!type) {
								continue; // no need to validate
							}
							if (!checker) { // uh-oh
								throw {
									name:"ValidationError",
									message:"No handler to validate type " + type
								};
							}

							result_ok = checker.validate(data[i]);
							if (!result_ok) {
								msg = "Invalid value for *" + i + "*, " + checker.instructions;
								this.messages.push(msg);
							}
						}
					}
					return this.hasErrors();
				},

				// helper
				hasErrors:function () {
					return this.messages.length !== 0;
				}
			};

			// checks for non-empty values
			validator.types.isNonEmpty = {
				validate:function (value) {
					return value !== "";
				},
				instructions:"the value cannot be empty"
			};

			// checks if a value is a number
			validator.types.isNumber = {
				validate:function (value) {
					return !isNaN(value) && value/Infinity === 0;
				},
				instructions:"the value can only be a valid number, e.g. 1, 3.14 or 2010"
			};

			// checks if the value contains only letters and numbers
			validator.types.isAlphaNum = {
				validate:function (value) {
					return !/[^a-z0-9]/i.test(value);
				},
				instructions:"the value can only contain characters and numbers, no special symbols"
			};

			var data = {
				first_name:"Super",
				last_name:"Man",
				age:"unknown",
				username:"o_O"
			};

			validator.config = {
				first_name:'isNonEmpty',
				age:'isNumber',
				username:'isAlphaNum'
			};

			validator.validate(data);

			if (validator.hasErrors()) {
				console.log(validator.messages.join("\n"));
			}

			// reference
			// http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#strategypatternjquery
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>


================================================
FILE: design-patterns/visitor.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Visitor
			 Description: Represent an operation to be performed on the elements of an object structure.
			 Visitor lets you define a new operation without changing the classes of the elements on which it operates.
			 */

			var Employee = function (name, salary, vacation) {
				var self = this;

				this.accept = function (visitor) {
					visitor.visit(self);
				};

				this.getName = function () {
					return name;
				};

				this.getSalary = function () {
					return salary;
				};

				this.setSalary = function (sal) {
					salary = sal;
				};

				this.getVacation = function () {
					return vacation;
				};

				this.setVacation = function (vac) {
					vacation = vac;
				};
			};

			var ExtraSalary = function () {
				this.visit = function (emp) {
					emp.setSalary(emp.getSalary() * 1.1);
				};
			};

			var ExtraVacation = function () {
				this.visit = function (emp) {
					emp.setVacation(emp.getVacation() + 2);
				};
			};

			// log helper
			var log = (function() {
				var log = "";

				return {
					add: function(msg) { log += msg + "\n"; },
					show: function() { alert(log); log = ""; }
				}
			})();

			//example
			function run() {

				var employees = [
					new Employee("John", 10000, 10),
					new Employee("Mary", 20000, 21),
					new Employee("Boss", 250000, 51)
				];

				var visitorSalary = new ExtraSalary();
				var visitorVacation = new ExtraVacation();

				for (var i = 0, len = employees.length; i < len; i++) {
					var emp = employees[i];

					emp.accept(visitorSalary);
					emp.accept(visitorVacation);
					log.add(emp.getName() + ": $" + emp.getSalary() +
							" and " + emp.getVacation() + " vacation days");
				}

				log.show();
			}

			// reference
			// http://www.dofactory.com/javascript/visitor-design-pattern
		</script>
	</body>
</html>

================================================
FILE: dom-and-browser/event-handling.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<button id="clickme">Click me: 0</button>
		<script>
			/* Title: Event Handling
			 Description: when you pass function A to function B as a parameter, function A is a callback function
			 */

			// antipattern
			/*var b = document.getElementById('clickme'),
			 count = 0;
			 b.onclick = function () {
			 count += 1;
			 b.innerHTML = "Click me: " + count;
			 };*/

			// preferred
			var b = document.getElementById('clickme');
			if (document.addEventListener) { // W3C
				b.addEventListener('click', myHandler, false);
			} else if (document.attachEvent) { // IE
				b.attachEvent('onclick', myHandler);
			} else { // last resort
				b.onclick = myHandler;
			}

			function myHandler(e) {
				var src, parts;
				// get event and source element
				e = e || window.event;
				src = e.target || e.srcElement;
				// actual work: update label
				parts = src.innerHTML.split(": ");
				parts[1] = parseInt(parts[1], 10) + 1;
				src.innerHTML = parts[0] + ": " + parts[1];
				// no bubble
				if (typeof e.stopPropagation === "function") {
					e.stopPropagation();
				}
				if (typeof e.cancelBubble !== "undefined") {
					e.cancelBubble = true;
				}
				// prevent default action
				if (typeof e.preventDefault === "function") {
					e.preventDefault();
				}
				if (typeof e.returnValue !== "undefined") {
					e.returnValue = false;
				}
			}
		</script>
	</body>
</html>

================================================
FILE: function-patterns/callback.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Callback patterns
			 Description: when you pass function A to function B as a parameter, function A is a callback function
			 */

			var complexComputation = function () { /* do some complex stuff and return a node */
			};

			var findNodes = function (callback) {
				var nodes = [];

				var node = complexComputation();

				// call if callback is callable
				if (typeof callback === "function") {
					callback(node);
				}

				nodes.push(node);
				return nodes;
			};

			// a callback function
			var hide = function (node) {
				node.style.display = "none";
			};

			// find the nodes and hide them as you go
			var hiddenNodes = findNodes(hide);

			// you can also use an anonymous function, like this:
			var blockNodes = findNodes(function (node) {
				node.style.display = 'block';
			});

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: function-patterns/callbacks-and-scope.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			var myapp = {};
			myapp.color = "green";
			myapp.paint = function (node) {
				node.style.color = this.color;
			};

			var findNodes = function (callback) {
				// ...
				if (typeof callback === "function") {
					callback(found);
				}
				// ...
			};

			var findNodes = function (callback, callback_obj) {
				// ...
				if (typeof callback === "function") {
					callback.call(callback_obj, found);
				}
				// ...
			};

			var findNodes = function (callback, callback_obj) {
				if (typeof callback === "string") {
					callback = callback_obj[callback];
				}

				// ...
				if (typeof callback === "function") {
					callback.call(callback_obj, found);
				}
				// ...
			};
		</script>
	</body>
</html>

================================================
FILE: function-patterns/configuration-objects.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Configuration objects
			 Description: keep control of function arguments and makes it easily configurable
			 */

			var conf = {
				username:"shichuan",
				first:"Chuan",
				last:"Shi"
			};
			addPerson(conf);

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: function-patterns/currying.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Currying
			 Description: used to create new functions dynamically by partially applying a set of arguments
			 in ECMAScript 5, you can use bind to implement curring.
			 */

			/***
			 function application
			 ***/
			// define a function
			var sayHi = function (who) {
				return "Hello" + (who ? ", " + who : "") + "!";
			};

			// invoke a function
			sayHi(); // "Hello!"
			sayHi('world'); // "Hello, world!"

			// apply a function
			sayHi.apply(null, ["hello"]); // "Hello, hello!"

			var alien = {
				sayHi:function (who) {
					return "Hello" + (who ? ", " + who : "") + "!";
				}
			};

			alien.sayHi('world'); // "Hello, world!"
			sayHi.apply(alien, ["humans"]); // "Hello, humans!"

			// the second is more efficient, saves an array
			sayHi.apply(alien, ["humans"]); // "Hello, humans!"
			sayHi.call(alien, "humans"); // "Hello, humans!"

			/***
			 partial application
			 ***/

			// for illustration purposes
			// not valid JavaScript

			// we have this function
			function add(x, y) {
				return x + y;
			}

			// and we know the arguments
			add(5, 4);

			// step 1 -- substitute one argument
			function add(5, y) {
				return 5 + y;
			}

			// step 2 -- substitute the other argument
			function add(5, 4) {
				return 5 + 4;
			}

			/***
			 currying
			 ***/

			// a curried add()
			// accepts partial list of arguments
			function add(x, y) {
				var oldx = x, oldy = y;
				if (typeof oldy === "undefined") { // partial
					return function (newy) {
						return oldx + newy;
					}
				}
				// full application
				return x + y;
			}

			// test
			typeof add(5); // "function"
			add(3)(4); // 7

			// create and store a new function
			var add2000 = add(2000);
			add2000(10); // 2010

			function schonfinkelize(fn) {
				var slice = Array.prototype.slice,
						stored_args = slice.call(arguments, 1);
				return function () {
					var new_args = slice.call(arguments),
							args = stored_args.concat(new_args);
					return fn.apply(null, args);
				};
			}

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate

			// Here's a generic curry function (from kybernetikos):
			// It's slightly more complex than the common examples of currying (e.g. the one above), but that's because
			//    the function can afterwards be called either in the normal way, or in the curried way.
			//    If you call a 3 argument curried function with it, the returned function *is also curried*.
			//    e.g. you can write func(arg1)(arg2)(arg3) or func(arg1, arg2, arg3) or func(arg1)(arg2, arg3) etc...

			/* the curry procedure needs to know how many arguments are required before it should calculate the result */
			function curry(func, minArgs) {
				if (minArgs == undefined) {
					minArgs = 1;
				}

				function funcWithArgsFrozen(frozenargs) {
					return function () {
						// could do an optimisation here - if called with no arguments
						// return exactly this function.
						var args = Array.prototype.slice.call(arguments);
						var newArgs = frozenargs.concat(args);
						if (newArgs.length >= minArgs) {
							return func.apply(this, newArgs);
						} else {
							return funcWithArgsFrozen(newArgs);
						}
					};
				}

				return funcWithArgsFrozen([]);
			}

			/* Here are some example uses - I use these with a functional immutable list structure implemented in js
			 but they also work ok for normal higher order functions over arrays.
			 */

			var plus = curry(function () {
				var result = 0;
				for (var i = 0; i < arguments.length; ++i) {
					result += arguments[i];
				}
				return result;
			}, 2);

			/* Now you can call
			 plus(3,2)         // normal call
			 plus(3)           // partial application (returns a function that adds 3 to its argument)
			 plus(3)(2)        // complete application (returns 5)
			 plus()(3)()()(2)  // returns 5
			 plus(3, 2, 4, 5)  // the normal call can optionally take more than the minimum number of arguments
			 plus(3)(2, 3, 5)  // the last application can too.
			 */

			var minus = curry(function (x) {
				var result = x;
				for (var i = 1; i < arguments.length; ++i) {
					result -= arguments[i];
				}
				return result;
			}, 2);

			/* flip switches the order of the first two arguments on a function.  It is curried itself and
			 the function it returns is curried too.  Particularly useful if you want a function that subtracts a number */

			var flip = curry(function (func) {
				return curry(function (a, b) {
					return func(b, a);
				}, 2);
			});

			/* for example
			 minus(5)             // returns a function that takes its argument away from 5
			 flip(minus)(5)       // returns a function that takes 5 away from its argument
			 */
		</script>
	</body>
</html>


================================================
FILE: function-patterns/enforcing-new-in-constructors.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			function Person() {
				var that = (this === window) ? {} : this;
				that.name = name;
				that.say = function () {
					return "I am " + that.name;
				};
				return that;
			}

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: function-patterns/function-call.html
================================================
<!doctype html>
<html lang="en">
  <head>
    <title>JavaScript Patterns</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script>
      // Title: 4 different ways to call function
      
      var foo, bar, baz, myapp;


      function foo(a, b) {
        return [this, a, b];
      };
      // using () operator
      // if the function is called without an explicit owner object
      // `this` keyword will refers to global
      // 
      // bar = [window, 1, 2]
      bar = foo(1, 2);
      console.log(bar);


      myapp = {
        baz: foo,
        onemore: function() {
          function insideTheClosure() {
            return this;
          }
          return [this, insideTheClosure()]
        }
      };

      // still using () operator
      // but now baz function belongs to myapp object
      //
      // bar = [myapp, 1, 2]
      bar = myapp.baz(1, 2);
      console.log(bar);

      // like in the first example we need to call function
      // within myapp like myapp.baz()
      // not just inside the object`s function
      // 
      // bar = [myapp, window]
      bar = myapp.onemore();
      console.log(bar);


      // using apply and call methods of the Function itself
      // there are almost the same
      // but apply could be useful in case we don't know arguments beforehand
      // 
      // bar = [myapp, 1, 2]
      bar = foo.call(myapp, 1, 2);
      console.log(bar);
      bar = foo.apply(myapp, [1, 2]);
      console.log(bar);


      /* Reference:
       * http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/JavaScript-5-ways-to-call-a-function.aspx
       */
    </script>
  </body>
</html>


================================================
FILE: function-patterns/immediate-functions.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Immediate functions
			 Description: syntax that enables function execution as soon as it is defined
			 */

			(function () {
				console.log('watch out!');
			}());

			//alternative with less parentheses
			!function () {
				console.log('watch out!');
			}();
			
			//another alternative with less parentheses
			+function () {
				console.log('watch out!');
			}();
			
			//crockfords the good part book way of doing this
			(function () {
				console.log('watch out!');
			}());


			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>


================================================
FILE: function-patterns/immediate-object-initialization.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Immediate object initialization
			 Description: this pattern is mainly suitable for one-off tasks
			 */

			({
				// here you can define setting values
				// a.k.a. configuration constants
				maxwidth:600,
				maxheight:400,

				// you can also define utility methods
				gimmeMax:function () {
					return this.maxwidth + "x" + this.maxheight;
				},

				// initialize
				init:function () {
					console.log(this.gimmeMax());
					// more init tasks...
				}
			}).init();

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>

================================================
FILE: function-patterns/init-time-branching.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Init-time branching
			 Description: branch code once during initialization
			 */

			// BEFORE
			/* var utils = {
			 addListener: function (el, type, fn) {
			 if (typeof window.addEventListener === 'function') {
			 el.addEventListener(type, fn, false);
			 } else if (typeof document.attachEvent !== 'undefined') {
			 el.attachEvent('on' + type, fn);
			 } else {
			 el['on' + type] = fn;
			 }
			 },
			 removeListener: function (el, type, fn) {
			 }
			 }; */

			// the interface
			var utils = {
				addListener:null,
				removeListener:null
			};

			// the implementation
			if (typeof window.addEventListener === 'function') {
				utils.addListener = function (el, type, fn) {
					el.addEventListener(type, fn, false);
				};
				utils.removeListener = function(el, type, fn) { 
					el.removeEventListener(type, fn, false); 
				};
			} else if (typeof document.attachEvent !== 'undefined') { // IE
				utils.addListener = function (el, type, fn) {
					el.attachEvent('on' + type, fn);
				};
				utils.removeListener = function (el, type, fn) {
					el.detachEvent('on' + type, fn);
				};
			} else { // older browsers
				utils.addListener = function (el, type, fn) {
					el['on' + type] = fn;
				};
				utils.removeListener = function (el, type, fn) {
					el['on' + type] = null;
				};
			}

			// reference
			// http://www.jspatterns.com/
			// http://shop.oreilly.com/product/9780596806767.do?sortby=publicationDate
		</script>
	</body>
</html>


================================================
FILE: function-patterns/memoization.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Memoization
			 Description: use function properties to avoid repeated computation
			 */

			// antipattern
			// reason see: https://github.com/shichuan/javascript-patterns/issues/6
			var myFunc = function (param) {
				if (!myFunc.cache[param]) {
					var result = {};
					// ... expensive operation ...
					myFunc.cache[param] = result;
				}
				return myFunc.cache[param];
			};

			// cache storage
			myFunc.cache = {};


			// preferred method 1
			// only one argument using param

			var myFunc = function (param) {
				if (!myFunc.cache.hasOwnProperty(param)) {
					var result = {};
					// ... expensive operation ...
					myFunc.cache[param] = result;
				}
				return myFunc.cache[param];
			};

			// cache storage
			myFunc.cache = {};


			// preferred method 2
			// multiple arguments using JSON stringify
			
			// this will only work correctly for primitive (and Array) arguments, 
			// since the order in which properties of Objects are enumerated is undetermined 
			// and can even change between enumerations. 
			// (a JSON encoder that sorts the keys won't have this issue).

			var myFunc = function () {
				var cachekey = JSON.stringify(Array.prototype.slice.call(arguments)),
						result;
				if (!myFunc.cache[cachekey]) {
					result = {};
					// ... expensive operation ...
					myFunc.cache[cachekey] = result;
				}
				return myFunc.cache[cachekey];
			};

			// cache storage
			myFunc.cache = {};


			// preferred method 3
			// multiple arguments using arguments.callee

			var myFunc = function (param) {
				var f = arguments.callee,
						result;
				if (!f.cache[param]) {
					result = {};
					// ... expensive operation ...
					f.cache[param] = result;
				}
				return f.cache[param];
			};

			// cache storage
			myFunc.cache = {};
		</script>
	</body>
</html>

================================================
FILE: function-patterns/partial-application.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Partial application
			 Description: the process of fixing a number of arguments to a function, producing another function of smaller arity
			 */

			var partialAny = (function(aps){

				// This function will be returned as a result of the immediately 
				// invoked function expression and assigned to the `partialAny` var.
				function func(fn){
					var argsOrig = aps.call(arguments, 1);
					return function() {
						var args = [],
							argsPartial = aps.call(arguments),
							i = 0;
						// Iterate over all the originally-spedicified arguments. If that
						// argument was the `partialAny._` placeholder, use the next just
						// passed-in argument, otherwise use the originally-specified 
						// argument.
						for ( ; i < argsOrig.length; i++ ) {
							args[i] = argsOrig[i] === func._
							? argsPartial.shift()
							: argsOrig[i];
						}

						// If any just-passed-in arguments remain, add them to the end.
						return fn.apply( this, args.concat( argsPartial ));
					};
				}

				// This is used as the placeholder argument.
				func._ = {};

				return func;
			})(Array.prototype.slice);

			// Slightly more legitimate example

			function hex( r, g, b ) {
				return '#' + r + g + b;
			}

			var redMax = partialAny( hex, 'ff', partialAny._, partialAny._);
			console.log(redMax('11','22')); // "#ff1122"

			// Because `_` is easier on the eyes than `partialAny._`, let's use
			// that instead. This is, of course, entirely optional, and the name
			// could just as well be `foo` or `PLACEHOLDER` instead of `_`.

			var __ = partialAny._;

			var greenMax = partialAny( hex, __, 'ff' );
			console.log(greenMax( '33', '44' )); 

			var blueMax = partialAny( hex, __, __, 'ff' );
			console.log(blueMax( '55', '66' ));

			var magentaMax = partialAny( hex, 'ff', __, 'ff' );
			console.log(magentaMax( '77' )); 

			// reference
			// http://msdn.microsoft.com/en-us/magazine/gg575560.aspx
		</script>
	</body>
</html>

================================================
FILE: function-patterns/returning-functions.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Returning functions
			 Description: one function returns another function or create another function on-demand
			 */

			var setup = function () {
				console.log(1);
				return function () {
					console.log(2);
				};
			};
			// using the setup function
			var my = setup(); // alerts 1
			my(); // alerts 2


			 
			// Your setup function can store some private data in a closure and use that data somehow.
			// Here setup() creates a counter function, which gives a next ID for example. But the count variable is not exposed.
			
			var setup = function () {
				var count = 0;
				return function () {
					return ++count;
				};
			};
			// usage
			var next = setup();
			//next(); // returns 1
			//next(); // returns 2
			//next(); // returns 3
			
			var newCodes = function(){  
			    var dCodes = 'one'; 
			    var dCodes2 = 'two';     
			    return [dCodes, dCodes2];  
			};
			
			var codes = newCodes();
			var dCodes = codes[0]; //access the first
			var dCodes2 = codes[1]; //access the second
			
			var newCodes = function(){  
			    var dCodes = 'one'; // Linked ICDs  
			    var dCodes2 = 'two'; //Linked CPTs       
			    return {
			        dCodes: dCodes,
			        dCodes2: dCodes2
			    };  
			};
			
			var codes = newCodes();
			var dCodes = codes.dCodes; //access the one called dcodes
			var dCodes2 = codes.dCodes2; //access the one called dcodes2
			
			// reference
			// http://www.jspatterns.com/returning-functions/
		</script>
	</body>
</html>


================================================
FILE: function-patterns/self-defining-functions.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Self-defining functions
			 Description: self-overwrite with new bodies to do less work from the second invocation and after
			 */

			var scareMe = function () {
				alert("Boo!");
				scareMe = function () {
					alert("Double boo!");
				};
			};

			// 1. adding a new property
			scareMe.property = "properly";
			// 2. assigning to a different name
			var prank = scareMe;
			// 3. using as a method
			var spooky = {
				boo:scareMe
			};
			// calling with a new name
			prank(); // "Boo!"
			prank(); // "Boo!"
			console.log(prank.property); // "properly"
			// calling as a method
			spooky.boo(); // "Boo!"
			spooky.boo(); // "Boo!"
			console.log(spooky.boo.property); // "properly"
			// using the self-defined function
			scareMe(); // Double boo!
			scareMe(); // Double boo!
			console.log(scareMe.property); // undefined
		</script>
	</body>
</html>

================================================
FILE: function-patterns/self-overwrite.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>

			function next() {
				var count = 1;
				next = function () {
					return ++count;
				};
				return count;
			}
			console.log(next()); // 1
			console.log(next()); // 2
		</script>
	</body>
</html>

================================================
FILE: general-patterns/access-to-global-object.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Access to the Global Object
			 * Description: access the global object without hard-coding the identifier window
			 */

			// access to the Global Object
			// this should work in ES3, ES5 and ES5-strict.
			var global = (function (g) {
				return g;
			})(this);

			// Test Cases
			// http://jsperf.com/globalx/7

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/avoiding-eval.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Avoiding eval()
			 * Description: avoid using eval()
			 */

			// antipattern 1
			var property = "name",
			    obj = { name: "John" };

			alert(eval("obj." + property));


			// preferred 1
			alert(obj[property]);


			/* antipattern 2
			 * It's also important to remember that passing strings to setInterval(), setTimeout(),
			 * and the Function() constructor is, for the most part, similar to using eval() and therefore should be avoided.
			 */
			setTimeout("myFunc()", 1000);
			setTimeout("myFunc(1, 2, 3)", 1000);


			// preferred 2
			setTimeout(myFunc, 1000);
			setTimeout(function () {
				myFunc(1, 2, 3);
			}, 1000);
			// in supported browsers (i.e. not IE)
			setTimeout(myFunc, 1000, 1, 2, 3);

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/avoiding-implied-typecasting.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Implied Typecasting
			 * Description: avoid implied typecasting
			 */

			var zero = 0;

			/* antipattern
			 * JavaScript implicitly typecasts variables when you compare them.
			 * That's why comparisons such as false == 0 or "" == 0 return true.
			 */
			if (zero == false) {
				// this block is executed...
			}


			// preferred
			/* To avoid confusion caused by the implied typecasting,
			 * always use the === and !== operators that check both the values and the type of the expressions you compare
			 */
			if (zero === false) {
				// not executing because zero is 0, not false
			}


			/* NOTE: There's another school of thought that subscribes to the opinion that it's redundant to use === when == is
			 * sufficient. For example, when you use typeof you know it returns a string, so there's no reason to use strict
			 * equality. However, JSLint requires strict equality; it does make the code look consistent and reduces the mental
			 * effort when reading code. ("Is this == intentional or an omission?")
			 */


			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>

================================================
FILE: general-patterns/built-in-prototypes.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: (Not) Augmenting Built-in Prototypes
			 * Description: it can seriously hurt maintainability, because it will make your code less predictable
			 */

			/* NOTE: You can make an exception of the rule only when all these conditions are met:

			 * 1. It's expected that future ECMAScript versions or JavaScript implementations will implement this functionality
			 *    as a built-in method consistently. For example, you can add methods described in ECMAScript 5 while waiting for
			 *    the browsers to catch up. In this case you’re just defining the useful methods ahead of time.
			 * 2. You check if your custom property or method doesn't exist already—maybe already implemented somewhere else in
			 *    the code or already part of the JavaScript engine of one of the browsers you support.
			 * 3. You clearly document and communicate the change with the team.
			 */
			if (typeof Object.prototype.myMethod !== "function") {
				Object.prototype.myMethod = function () {
					// implementation...
				};
			}

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>

================================================
FILE: general-patterns/conditionals.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Conditionals
			 * Description: pattern and antipattern of using if else
			 */

			/* NOTE: Paul Irish states that the first statement (normal pattern) is only an antipattern when optimizing for
			 * low-bandwidth source (such as for a bookmarklet).
			 * Using the normal pattern will generally outperform the regex (alternative method 1) in a loop,
			 * and is faster than the object literal (alternative method 2) for lower numbers of conditions,
			 * they generally even out around 10 conditions.
			 * See http://jsperf.com/if-this-or-that
			 */

			// normal pattern
			if (type === 'foo' || type === 'bar') {
			}


			// alternative method 1 - regex test
			if (/^(foo|bar)$/.test(type)) {
			}


			// alternative method 2 - object literal lookup (smaller if < 5 items)
			if (({foo:1, bar:1})[type]) {
			}


			/* alternative method 3 - binary-search-like approach
			 * This approach is best when there are ranges of values for which to test
			 */
			if (value < 6) {
				if (value < 3) {
					if (value == 0) {
						return result0;
					} else if (value == 1) {
						return result1;
					} else {
						return result2;
					}
				} else {
					if (value == 3) {
						return result3;
					} else if (value == 4) {
						return result4;
					} else {
						return result5;
					}
				}
			} else {
				if (value < 8) {
					if (value == 6) {
						return result6;
					} else {
						return result7;
					}
				} else {
					if (value == 8) {
						return result8;
					} else if (value == 9) {
						return result9;
					} else {
						return result10;
					}
				}
			}


			/* alternative method 4 - object/array lookup tables
			 * Most useful when there is logical mapping between a single key and a single value
			 */
			if (value == 0) {
				return result0;
			} else if (value == 1) {
				return result1;
			} else if (value == 2) {
				return result2;
			}
			
			// define the array of results
			var results = [result0, result1, result2];
			// return the correct result
			return results[value];
			
			
			/* alternative method 5 - only using logical operators
			 * Shorter way to use simple statements
			 */
			var 
				type = 'foo',
				type2 = 'bar',
				result = 0;
				
			type == 'foo' && result++;
			console.log(result); // 1
			!type == 'foo' || result++;
			console.log(result); // 2
			type == 'foo' && type2 == 'bar' && result++;
			console.log(result); //3
			type == 'foo' && type2 == 'bar' && result == 3 && (result=0); //parentheses avoid "invalid assignment left-hand side" error
			console.log(result); //0
			type == 'OOF' || result++; //equivalent: type != 'OOF' && result++;
			console.log(result); //1			


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/for-in-loops.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: for-in loops
			 * Description: optimized for-in loops
			 */
			// the object
			var man = {
				hands:2,
				legs:2,
				heads:1
			};
			// somewhere else in the code
			// a method was added to all objects
			if (typeof Object.prototype.clone === 'undefined') {
				Object.prototype.clone = function () {
				};
			}
			
			// antipattern
			// for-in loop without checking hasOwnProperty()
			for (var i in man) {
				console.log(i, ":", man[i]);
			}
			/*
			 * result in the console
			 * hands : 2
			 * legs : 2
			 * heads : 1
			 * clone: function()
			 */
			// preferred 1
			for (var i in man) {
				if (man.hasOwnProperty(i)) { // filter
					console.log(i, ":", man[i]);
				}
			}
			/*
			 * result in the console
			 * hands : 2
			 * legs : 2
			 * heads : 1
			 */
			// preferred 2
			// benefit is you can avoid naming collisions in case the `man` object has redefined `hasOwnProperty`
			for (var i in man) {
				if (Object.prototype.hasOwnProperty.call(man, i)) { // filter
					console.log(i, ":", man[i]);
				}
			}
			// preferred 3
			// use a local variable to "cache" `Object.prototype.hasOwnProperty`
			var i,
					hasOwn = Object.prototype.hasOwnProperty;
			for (i in man) {
				if (hasOwn.call(man, i)) { // filter
					console.log(i, ":", man[i]);
				}
			}
			
			
			//Preferred 4 
			/* Check if object has properties before print output
			 *  using Object.keys(obj) and length built ins. A good method for 
			 *  not wasting resources and avoiding errors with larger objects
			 */  
			if (Object.keys(man).length > 0){
			     for (var item in man)
				 console.log(item,':',man[item]);
			} else { 
			    console.log('Empty Object');}
			
			/*	
			 * hands : 2
			 * legs : 2
			 * heads : 1
			 * clone : function() {
			 *		    }
			 */
			
			
			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/for-loops.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: for loops
			 * Description: optimized for loops
			 */

			// sub-optimal loop
			for (var i = 0; i < myarray.length; i++) {
				// do something with myarray[i]
			}

			// optimization 1 - cache the length of the array with the use of `max`
			for (var i = 0, max = myarray.length; i < max; i++) {
				// do something with myarray[i]
			}


			// optimization 2 - use single var pattern for consistency
			// NOTE: A drawback is that it makes it a little harder to copy and paste whole loops while refactoring code.
			var i = 0,
					max,
					myarray = [];

			for (i = 0, max = myarray.length; i < max; i++) {
				// do something with myarray[i]
			}


			// optimization 3 - substitute `i++` with `i = i + 1`  or `i += 1` to avoid excessive trickiness
			var i = 0,
					max,
					myarray = [];

			for (i = 0, max = myarray.length; i < max; i += 1) {
				// do something with myarray[i]
			}


			// preferred 1
			var i, myarray = [];
			for (i = myarray.length; i--;) {
				// do something with myarray[i]
			}


			// preferred 2
			var myarray = [],
					i = myarray.length;
			while (i--) {
				// do something with myarray[i]
			}


			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>

================================================
FILE: general-patterns/function-declarations.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Function Declarations
			 * Description: creating anonymous functions and assigning them to a variable
			 */

			// antipattern
			// there is one benefit for this type of function decalaration:
			// you can call getData () before the declaration. 
			function getData() {
			}


			// preferred
			/* Benefits:
			 * 1. Makes it easier to understand "functions as an object".
			 * 2. It enforces good semicolon habits.
			 * 3. Doesn't have much of the baggage traditionally associated with functions and scope.
			 */
			var getData = function () {
			};


			// named function expression
			/* Benefits:
			 * 1. Provides the debugger with an explicit function name: helps stack inspection.
			 * Issues:
			 * 3. Can break IE, coffeescript doesn't do function names:
			 *    https://github.com/jashkenas/coffee-script/issues/366
			 */
			var getData = function getData () {
			};

                        // named function expression + 'F'
			/* Benefits:
			 * 1. Gets rid of (anonymous function) in stack traces
			 * 2. Doesn't break an IE (well, unless there's a function name collision of the sort described here: https://github.com/jashkenas/coffee-script/issues/366#issuecomment-242134)
			 */
			var getData = function getDataF () {
			};


			// References
			// http://ejohn.org/blog/javascript-as-a-first-language/
			// http://kangax.github.com/nfe/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/global-import.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: The Problem with Globals
			 * Description: You can pass some global objects inside a function.
			 */

			(function ($, YAHOO) {
				// now have access to globals jQuery (as $) and YAHOO in this code
			}(jQuery, YAHOO));

			// References
			// http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
		</script>
	</body>
</html>

================================================
FILE: general-patterns/globals.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: The Problem with Globals
			 * Description: The problem is that they are shared among all the code in your JavaScript application or web page
			 */

			// antipattern 1
			function sum(x, y) {
				// implied global
				result = x + y;
				return result;
			}


			// preferred 1
			function sum(x, y) {
				// a variable declared inside of a function is local to that function and not available outside the function
				var result = x + y;
				return result;
			}


			// antipattern 2
			function foo() {
				var a = b = 0;
				// ...
			}

			// the preceding code snippet will behave as if you've typed the following
			var a = (b = 0);


			// preferred 2
			function foo() {
				var a, b;
				// ...
				a = b = 0; // both local
			}

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/hoisting.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Hoisting
			 * Description: var statements anywhere in a function act as if the variables were declared at the top of the function
			 */

			// antipattern
			wontchange = "global"; // global variable
			willchange = "global"; // global variable
			function func_bad() {
				alert(wontchange); // "global"
				alert(willchange); // "undefined" due to the var below
				var willchange = "local"; // This rescopes willchange inside this function
				alert(willchange); // "local"
			}
			func_bad();

			// the preceding code snippet will behave as if it were implemented like so:
			wontchange = "global"; // global variable
			willchange = "global"; // global variable
			function func() {
				// This still rescopes, but it is a lot more explicit
				var willchange; // same as -> var willchange = undefined;
				alert(wontchange); // "global"
				alert(willchange); // "undefined"
				willchange = "local";
				alert(willchange); // "local"
			}
			func();


			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>

================================================
FILE: general-patterns/iife-for-loop.html
================================================
<!doctype html>
<html lang="en">
    <head>
        <title>JavaScript Patterns</title>
        <meta charset="utf-8">
    </head>
    <body>
        <script>
            /* Title: iife for loops
             * Description: loops that make use of counters as expected
             */

            // this will log 'regular loop 5'
            for (var i = 0; i < 5; i++) {
              setTimeout(function() {
                console.log('regular loop', i);
              }, 3000);
            }

            // this will log 'iife loop 1', 'iife loop 2', 'iife loop 3', 'iife loop 4'
            for (var i = 0; i < 5; i++) {
              (function(n) {
                setTimeout(function() {
                  console.log('iife loop', n);
                }, 3000);
              })(i);
            }

            // same results as the iife loop. Let isn't supported by all javascript versions
            for (let i = 0; i < 5; i++) {
              setTimeout(function() {
                console.log('let loop', i);
              }, 3000);
            }

            // References
            // http://benalman.com/news/2010/11/immediately-invoked-function-expression/
        </script>
    </body>
</html>

================================================
FILE: general-patterns/map-and-filter-by-reduce.html
================================================
<!doctype html>
<html lang="en">
<head>
    <title>JavaScript Patterns</title>
    <meta charset="utf-8">
</head>
<body>
<script>
  /* Title: Map and Filter By Reduce
   * Description: Combine map and filter with reduce
   */

  // Basic example
  const euro = [29.76, 41.85, 46.5];
  const above30 = euro.reduce((total, amount) => {
    if (amount > 30) {
      total.push(amount);
    }
    return total;
  }, []);
  console.log('above30', above30);

  // Using async/await
  async function foo() {
    try {
      var values = await getValues();

      return await values.reduce(async function(values, value) {
        values = await values;
        value = await asyncOperation(value);
        console.log(value);
        values.push(value);
        return values;
      }, []);
    } catch (err) {
      console.log('We had an ', err);
    }
  }

  // References
  // https://medium.freecodecamp.org/reduce-f47a7da511a9
  // https://code.tutsplus.com/tutorials/a-primer-on-es7-async-functions--cms-22367
</script>
</body>
</html>

================================================
FILE: general-patterns/minimizing-globals.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Minimizing Globals
			 Description: they are declared outside of any function or simply used without being declared
			 */

			myglobal = "hello"; // antipattern
			console.log(myglobal); // "hello"
			console.log(window.myglobal); // "hello"
			console.log(window["myglobal"]); // "hello"
			console.log(this.myglobal); // "hello"

			// If you have to (gun to your head) use globals like jQuery does think of using a prefix and holding all your information in an object
			prefix_myglobal = {
			    method: function () {},
			    property: "hello"
			};

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/parseint.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Number Conversions with parseInt()
			 Description: use the second radix parameter
			 */

			// pattern 1
			/* NOTE: in this example, if you omit the radix parameter like parseInt(year), the returned value will be 0,
			 * because "09" assumes octal number (as if you did parseInt( year, 8 )) and 09 is not a valid digit in base 8.
			 */
			 //if we omit the radix parameter then the returned value is not zero, it takes base 10 in chrome console.please check

			var month = "06",
			year = "09";
			month = parseInt(month, 10);
			year = parseInt(year, 10);


			// pattern 2
			/* NOTE: if you're expecting input such as “08 hello”, parseInt() will return a number, whereas the others will fail
			 * with NaN.
			 If the input string begins with "0", radix is eight (octal) or 10 (decimal).  
			 Exactly which radix is chosen is *implementation-dependent*.  
			 ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.  For this reason always specify a radix when using parseInt.
			 */
			+"08" // result is 8
			Number("08") // 8
			
			//pattern 3
			/* NOTE: Bit operator parsing to int and chunk float vars, if a string has characters it return zero (0)
			 *
			 */
			("789"|0) // => 789
			("sds"|0) // => 0
			(8.45|0) // => 8
			("8.55"|0) // => 8

			// References
			// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/shim-sniffing.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Shim Sniffing
			 * Description: 
			 */

			// antipattern
			Array.prototype.map = function() {
				// stuff
			};

			// better 
			if (!Array.prototype.map) {
				Array.prototype.map = function() {
					// stuff
				};
			}

			// even better
			if (typeof Array.prototype.map !== "function") {
				Array.prototype.map = function() {
					// stuff
				}
			}


			// If use either native or your own implementation, but not others:
			// When you call toString() of a native function it should return a string with a function that has a body of [native code] 

			// by default there is white spaces and new lines issue
			console.log(Array.prototype.map.toString().replace(/\s/g, '*'));
			// "*function*map()*{*****[native*code]*}*"  // IE
			// "function*map()*{*****[native*code]*}" // FF
			// "function*map()*{*[native*code]*}" // Chrome

			// a proper check can fix the problem
			console.log(Array.prototype.map.toString().replace(/\s/g, ''));
			// "functionmap(){[nativecode]}"

			// a reusable shim() function
			function shim(o, prop, fn) {
				var nbody = "function" + prop + "(){[nativecode]}";
				if (o.hasOwnProperty(prop) &&
					o[prop].toString().replace(/\s/g, '') === nbody) {
					// native!
					return true;
				}
				// shim
				o[prop] = fn;
			}

			// this is native, cool
			shim(
				Array.prototype, 'map',
				function(){/*...*/}
			); // true

			// this is new
			shim(
				Array.prototype, 'mapzer',
				function(){console.log(this)}
			);

			[1,2,3].mapzer(); // alerts 1,2,3

			// References
			// http://www.jspatterns.com/shim-sniffing/
		</script>
	</body>
</html>


================================================
FILE: general-patterns/single-var-pattern.html
================================================
<!doctype html>
<html lang="en">
  <head>
    <title>JavaScript Patterns</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script>
      /* Title: Single var Pattern
       Description: use one var statement and declare multiple variables
       */

      /* Benefits:
       * 1. Provides a single place to look for all the local variables needed by the function
       * 2. Prevents logical errors when a variable is used before it's defined
       * 3. Helps you remember to declare variables and therefore minimize globals
       * 4. Is less code (to type and to transfer over the wire)
       */

      function func() {
        var a = 1
          , b = 2
          , sum = a + b
          , myobject = {}
          , i
          , j;

        // function body...
      }

      function updateElement() {
        var el = document.getElementById("result")
          , style = el.style;
        // do something with el and style...
      }
      
      // Preferred way 
      // Move commas BEFORE vars
      // You'll not forget to add one when adding variable to the end of list
      function func() {
        var a = 1
            , b = 2
            , sum = a + b
            , myobject = {}
            , i
            , j;

        // function body...
      }

      // References
      // http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
    </script>
  </body>
</html>

================================================
FILE: general-patterns/switch-pattern.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: switch Pattern
			 Description: improve the readability and robustness of your switch statements
			 */

			/* Style conventions:
			 * 1. Aligning each `case` with `switch` (an exception to the curly braces indentation rule).
			 * 2. Indenting the code within each case.
			 * 3. Ending each `case` with a clear `break`;.
			 * 4. Avoiding fall-throughs (when you omit the break intentionally). If you're absolutely convinced
			 *    that a fall-through is the best approach, make sure you document such cases, because they might
			 *    look like errors to the readers of your code.
			 * 5. Ending the `switch` with a `default`: to make sure there's always a sane result even if none of 
			 *    the cases matched.
			 */

			//antipattern
			var inspect_me = 0,
					result = '';
			switch (inspect_me) {
			case 0:
				result = "zero";
				break;
			case 1:
				result = "one";
				break;
			default:
				result = "unknown";
			}

			//preferred 1,
			//'cause it is much faster and easy to reuse and read
			//avoid to use switch
			var results = {
				0: "zero",
				1: "one"
			};

			result = results[inspect_me] || "unknown";

			//preferred 2
			var resultFuncs = {
				0: function () {
					//some code for "zero" case
					return "zero";
				},
				1: function () {
					//some code for one case
					return "one";
				}
			};

			result = (resultFuncs[inspect_me] || function () {
				//some code for default case
				return "unknown";
			})();

			// References
			// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
		</script>
	</body>
</html>


================================================
FILE: img/.gitignore
================================================
!.gitignore



================================================
FILE: index.html
================================================
<!doctype html>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!-- Consider adding a manifest.appcache: h5bp.com/d/Offline -->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">

  <!-- Use the .htaccess and remove these lines to avoid edge case issues.
       More info: h5bp.com/b/378 -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>JavaScript Patterns</title>
  <meta name="description" content="JavaScript patterns and antipatterns collection">
  <meta name="author" content="Shi Chuan">

  <!-- Mobile viewport optimized: h5bp.com/viewport -->
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <!-- Place favicon.ico and apple-touch-icon.png in the root directory: mathiasbynens.be/notes/touch-icons -->
  <link href='http://fonts.googleapis.com/css?family=Tinos:400,700,400italic' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/style.css">
  
  <!-- More ideas for your <head> here: h5bp.com/d/head-Tips -->

  <!-- All JavaScript at the bottom, except this Modernizr build incl. Respond.js
       Respond is a polyfill for min/max-width media queries. Modernizr enables HTML5 elements & feature detects; 
       for optimal performance, create your own custom Modernizr build: www.modernizr.com/download/ -->
  <script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>

<body>
  <a class="fork" href="https://github.com/shichuan/javascript-patterns">
    <img src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
  </a>
  <header>
    <div class="clearfix">
      <h1>JavaScript Patterns Collection</h1> 
      <div id="btns">
      <span  class='st_sharethis_hcount' displayText='ShareThis'></span><span  class='st_twitter_hcount' displayText='Tweet'></span><span  class='st_facebook_hcount' displayText='Facebook'></span><span  class='st_plusone_hcount' ></span>
      </div>
    </div>
    <img src="img/js-patterns.png" alt="JS Patterns" title="JS Patterns" />
    <nav id="toc" class="sticky">
      <ul>
        <li><a href="#general-patterns">General Patterns</a></li>
        <li><a href="#jquery-patterns">jQuery Patterns</a></li>
        <li><a href="#jquery-plugin-patterns">jQuery Plugin Patterns</a></li>
        <li><a href="#literals-and-constructor">Literals and Constructor Patterns</a></li>
        <li><a href="#function-patterns">Function Patterns</a></li>
        <li><a href="#object-creation-patterns">Object Creation Patterns</a></li>
        <li><a href="#code-reuse-patterns">Code Reuse Patterns</a></li> 
        <li><a href="#design-patterns">Design Patterns</a></li>  
      </ul>
    </nav>
  </header>
  <div role="main">
    <section id="intro">
      <p>A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM and browser patterns (<em>upcoming</em>).</p>
      Patterns collected while developing <a href="http://www.xigan.com">喜感网</a>.</p>
    </section>
    <section id="general-patterns">
      <h2>General Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/function-declarations.html" target="_blank">Function Declarations</a> - creating anonymous functions and assigning them to a variable</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/conditionals.html" target="_blank">Conditionals</a> - pattern and antipattern of using if else</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/access-to-global-object.html" target="_blank">Access to the Global Object</a> - access the global object without hard-coding the identifier window</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/single-var-pattern.html" target="_blank">Single var Pattern</a> - use one var statement and declare multiple variables</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/hoisting.html" target="_blank">Hoisting</a> - var statements anywhere in a function act as if the variables were declared at the top of the function</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/for-loops.html" target="_blank">for loops</a> - optimized for loops</li> 
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/for-in-loops.html" target="_blank">for-in loops</a> - optimized for-in loops</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/built-in-prototypes.html" target="_blank">(Not) Augmenting Built-in Prototypes</a> - only augment built-in prototypes when certain conditions are met</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/switch-pattern.html" target="_blank">switch Pattern</a> - improve the readability and robustness of your switch statements</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/avoiding-implied-typecasting.html" target="_blank">Implied Typecasting</a> - avoid implied typecasting</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/avoiding-eval.html" target="_blank">Avoiding eval()</a> - avoid using eval()</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/parseint.html" target="_blank">Number Conversions with parseInt()</a> - use the second radix parameter</li>     
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/minimizing-globals.html" target="_blank">Minimizing Globals</a> - create and access a global variable in a browser environment</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/globals.html" target="_blank">The Problem with Globals</a> - various problems with globals</li>
      </ul>
    </section>
    
    <section id="jquery-patterns">
      <h2>jQuery Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/requery.html" target="_blank">requery</a> - avoid requery by using jQuery chaining</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/append.html" target="_blank">append</a> - use string concatenate and set innerHTML</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/data.html" target="_blank">data</a> - pattern and antipattern of using data</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/context-and-find.html" target="_blank">context and find</a> - use find over context</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/detach.html" target="_blank">detach</a> - take element off the DOM while manipulating them</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/event-delegation.html" target="_blank">event delegation</a> - event delegation pattern and antipattern</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/cache-selector.html" target="_blank">selector cache</a> - using selector cache to avoid requery</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/window-scroll-event.html" target="_blank">window scroll event</a> -  avoid attaching handlers to the window scroll event</li>
      </ul>
      <h3>Selector</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/left-and-right.html" target="_blank">Left and Right</a> - specific on the right, light on the left</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/decending-from-id.html" target="_blank">Decending from id</a> - be more specific</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/universal-selector.html" target="_blank">Universal Selector</a> - use of universal selector</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/specific-when-needed.html" target="_blank">Be Specific when Needed</a> - be specific only when needed</li>
      </ul>
      <h3 id="jquery-pubsub">Publish–subscribe</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-custom-events.html" target="_blank">Method 1</a> - custom events using .on() and .off()</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-callback.html" target="_blank">Method 2</a> - using jQuery 1.7's $.Callbacks() feature</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-observable.html" target="_blank">Method 3</a> - using jQuery UI $.Observable</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-plugin.html" target="_blank">Method 4</a> - third-party plugins</li>
      </ul>
    </section>

    <section id="jquery-plugin-patterns">
      <h2>jQuery Plugin Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/basic.html" target="_blank">Basic</a> - the most basic pattern</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/extend.html" target="_blank">Extend</a> - enables you to define multiple functions at once and which sometimes make more sense semantically</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/lightweight.html" target="_blank">Lightweight</a> - perfect as a generic template for beginners and above</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/namespaced-starter.html" target="_blank">Namespaced pattern</a> - to avoid collisions and improve code organization when working with components under another namespace</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/prototypal-inheritance.html" target="_blank">Prototypal inheritance</a> - prototypal inheritance with the DOM-to-Object bridge pattern</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/best-options.html" target="_blank">Best options</a> - globally/Per-call overridable options for greater option customization</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/custom-events.html" target="_blank">Custom events (Pseudo Pub/Sub)</a> - for better application decoupling</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/highly-configurable-mutable.html" target="_blank">'Highly configurable' mutable</a> - define plugin’s logic using a constructor and an object literal defined on its prototype</li>
        
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/ui-widget-factory.html" target="_blank">UI Widget factory</a> - for building complex, stateful plugins based on object-oriented principles</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/ui-widget-factory-bridge.html" target="_blank">UI Widget factory "bridge"</a> - the bridge serves as a middle layer between a JavaScript object that is created using $.widget and jQuery’s API</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/ui-widget-factory-mobile.html" target="_blank">UI Widget factory for jQuery mobile</a> - demonstrating best practices for building mobile widgets</li>

        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/jquery-plugin-patterns/ui-widget-requirejs-module.html" target="_blank">UI Widget + RequireJS module</a> - for wrapping jQueryUI widgets inside RequireJS compatible modules</li>
        
        <li><a href="https://github.com/shichuan/javascript-patterns/tree/master/jquery-plugin-patterns/amd-commonjs" target="_blank">Universal Module Definition pattern</a> - create AMD and CommonJS compatible plugin modules which are compatible with a number of different script loaders</li>
      </ul>    
    </section>
    
    <section id="literals-and-constructor">
      <h2>Literals and Constructors Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/object-literal.html" target="_blank">Object literal</a> - use the simpler and reliable object literal instead of new Object();</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/enforcing-new.html" target="_blank">Enforcing new</a> - when you forget `new`, `this` inside the constructor will point to the global object</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/array-literal.html" target="_blank">Array literal</a> - use array literal notation to avoid potential errors when creating dynamic arrays at runtime</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/json.html" target="_blank">Working with JSON</a> - use library from JSON.org, YUI, jQuery instead of eval for parsing</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/primitive-wrappers.html" target="_blank">Primitive wrappers</a> - try to use the primitive without wrapper</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/literals-and-constructors/regular-expression-literal.html" target="_blank">Regular expression literal</a> - try to use the shorter literal notation</li>
      </ul>
    </section>

    <section id="function-patterns">
      <h2>Function Patterns</h2>
      <h3>API Patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/callback.html" target="_blank">Callback patterns</a> - when you pass function A to function B as a parameter, function A is a callback function</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/configuration-objects.html" target="_blank">Configuration objects </a>- keep control of function arguments and makes it easily configurable</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/returning-functions.html" target="_blank">Returning functions </a>- one function returns another function or create another function on-demand</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html" target="_blank">Currying</a> - used to create new functions dynamically by partially applying a set of arguments</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/partial-application.html" target="_blank">Partial application</a> - the process of fixing a number of arguments to a function, producing another function of smaller arity</li>
        
      </ul>
      
      <h3>Initialization patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/immediate-functions.html" target="_blank">Immediate functions</a> - syntax that enables function execution as soon as it is defined</li> 
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/immediate-object-initialization.html" target="_blank">Immediate object initialization</a> - this pattern is mainly suitable for one-off tasks</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/init-time-branching.html" target="_blank">Init-time branching</a> - branch code once during initlization initialization</li>
      </ul>
      
      <h3>Performance patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/memoization.html" target="_blank">Memoization</a> - use function properties to avoid repeated computation</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/self-defining-functions.html" target="_blank">Self-defining functions</a> - self-overwrite with new bodies to do less work from the second invocation and after</li>
      </ul>
    </section>

    <section id="object-creation-patterns">
      <h2>Object Creation Patterns</h2>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/namespace.html" target="_blank">Namespace</a> - namespaces help reduce the number of globals required and avoid naming collisions or excessive name prefixing</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/declaring-dependencies.html" target="_blank">Declaring Dependencies</a> - it's good to declare the modules your code relies on at the top</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/private-properties-and-methods.html" target="_blank">Private Properties and Methods</a> - JavaScript doesn't have special syntax for private members, you can implement them using a closure</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/revelation.html" target="_blank">Revelation Pattern</a> - it is about having private methods, which you also expose as public methods</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/module.html " target="_blank">Module Pattern</a> - all the methods are kept private and you only expose those that you decide at the end</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/sandbox.html" target="_blank">Sandbox</a> - it provides an environment for the modules to work without affecting other modules and their personal sandboxes</li>        
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/static-members.html" target="_blank">Static Members</a> - public and private static members</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/object-constants.html" target="_blank">Object Constants</a> - an implementation of a contant object provides set, inDefined and get methods</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/chaining.html" target="_blank">Chaining Pattern</a> - it enables you to call methods on an object one after the other</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/object-creation-patterns/sugar-method.html" target="_blank">method() Method</a> - adding convenient funcationality to a language</li>
      </ul>
    </section>

    <section id="code-reuse-patterns">
      <h2>Code Reuse Patterns</h2>
      <h3>Classical Patterns (patterns that should generally be avoided)</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/cp1-default.html" target="_blank">The default pattern</a> - create an object using the Parent() constructor and assign this object to the Child()'s prototype</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/cp2-rent-a-constructor.html" target="_blank">Rent a constructor</a> - it borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/cp3-rent-and-set-prototype.html" target="_blank">Rent and Set Prototype</a> - restricts object creation for a class to only one instance</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/cp4-share-the-prototype.html" target="_blank">Share the Prototype</a> - restricts object creation for a class to only one instance</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/cp5-a-temporary-constructor.html" target="_blank">A Temporary Constructor</a> - first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/klass.html" target="_blank">Klass</a> - generally a pattern that should be avoided unless one is more comfortable with class than prototype</li>
      </ul>
      <h3>Preferred Patterns</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/prototypal-inheritance.html" target="_blank">Prototypal Inheritance</a> - objects inherit from other objects</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/inheritance-by-copying-properties.html" target="_blank">Inheritance by Copying Properties</a> - an object gets functionality from another object, simply by copying it</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/mix-ins.html" target="_blank">Mix-ins</a> - copy from any number of objects and mix them all into a new object</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/code-reuse-patterns/borrowing-methods.html" target="_blank">Borrowing Methods</a> - reuse one or two methods of an existing object without forming a parent-child relationship with that object</li>
      </ul>
    </section>
    
    <section id="design-patterns">
      <h2>Design Patterns</h2>
      <h3>Creational</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/builder.html" target="_blank">Builder</a> - constructs complex objects by separating construction and representation</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/factory.html" target="_blank">Factory method</a> - creates objects without specifying the exact class to create</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/singleton.html" target="_blank">Singleton</a> - restricts object creation for a class to only one instance</li>
      </ul>
      <h3>Structural</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/decorator.html" target="_blank">Decorator</a> - dynamically adds/overrides behaviour in an existing method of an object</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/facade.html" target="_blank">Facade</a> - provides a simplified interface to a large body of code</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/proxy.html" target="_blank">Proxy</a> - provides a placeholder for another object to control access, reduce cost, and reduce complexity</li>
      </ul>
      <h3>Behavioral</h3>
      <ul>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/chain-of-responsibility.html" target="_blank">Chain of responsibility</a> - delegates commands to a chain of processing objects</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/command.html" target="_blank">Command</a> - creates objects which encapsulate actions and parameters</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/iterator.html" target="_blank">Iterator</a> - implements a specialized language</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/mediator.html" target="_blank">Mediator</a> - allows loose coupling between classes by being the only class that has detailed knowledge of their methods</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/observer.html" target="_blank">Observer</a> - is a publish/subscribe pattern which allows a number of observer objects to see an event</li>
        <li><a href="https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/strategy.html" target="_blank">Strategy</a> - allows one of a family of algorithms to be selected on-the-fly at runtime</li>
      </ul>
    </section>
    
    <section>
      <h2><em>References</em></h2>
      <ol>    
        <li>
        The Essentials of Writing High Quality JavaScript<br />
        <a href="http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/" target="_blank">http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/</a>
        </li>
        <li>
        JSPatterns<br />
        <a href="http://www.jspatterns.com/" target="_blank">http://www.jspatterns.com/</a>
        </li>
        <li>
        jQuery Anti-Patterns for Performance & Compression<br />
        <a href="http://paulirish.com/2009/perf/" target="_blank">http://paulirish.com/2009/perf/</a>
        </li>
        <li>
        How DRY Affects JavaScript Performance<br />
        <a href="http://velocityconf.com/velocityeu/public/schedule/detail/21634" target="_blank">http://velocityconf.com/velocityeu/public/schedule/detail/21634</a>
        </li>
        <li>
        Object Oriented JavaScript<br />
        <a href="http://www.packtpub.com/object-oriented-javascript/book" target="_blank">http://www.packtpub.com/object-oriented-javascript/book</a>
        </li>
        <li>
        JavaScript Patterns<br />
        <a href="http://shop.oreilly.com/product/9780596806767.do" target="_blank">http://shop.oreilly.com/product/9780596806767.do</a>
        </li>
        <li>
        JavaScript: The Good Parts<br />
        <a href="http://shop.oreilly.com/product/9780596517748.do" target="_blank">http://shop.oreilly.com/product/9780596517748.do</a>
        </li>
        <li>
        Pro JavaScript Design Patterns<br />
        <a href="http://jsdesignpatterns.com/" target="_blank">http://jsdesignpatterns.com/</a>
        </li>
        <li>
        Essential JavaScript Design Patterns For Beginners, Volume 1.<br />
        <a href="http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/" target="_blank">http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/</a>
        </li>
        <li>
        Eloquent JavaScript<br />
        <a href="http://eloquentjavascript.net/" target="_blank">http://eloquentjavascript.net/</a>
        </li>
      </ol>
    </section>
  </div>
  <footer>
    by <a href="http://twitter.com/#!/shichuan">@shichuan</a> from <a href="http://www.xigan.com">喜感网</a>
  </footer>


  <!-- JavaScript at the bottom for fast page loading -->
  <script type="text/javascript">var switchTo5x=false;</script><script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
  <script type="text/javascript">
    stLight.options({
      publisher:'44fc3536-fd12-4c07-970d-6654da9a2d6c',
      st_url:'http://shichuan.github.com/javascript-patterns/'
    });
  </script>
  
  <!-- Asynchronous Google Analytics snippet. Change UA-XXXXX-X to be your site's ID.
       mathiasbynens.be/notes/async-analytics-snippet -->
  <script>
    var _gaq=[['_setAccount','UA-2773745-18'],['_trackPageview'],['_trackPageLoadTime']];
    (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
    g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
    s.parentNode.insertBefore(g,s)}(document,'script'));
  </script>

  <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6.
       chromium.org/developers/how-tos/chrome-frame-getting-started -->
  <!--[if lt IE 7 ]>
    <script defer src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script>
    <script defer>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script>
  <![endif]-->

</body>
</html>


================================================
FILE: jquery-patterns/append.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: append
			 * Description: use string concatenate and set innerHTML. Note that it is recommended to use the 
			 * array.join technique to concatenate long strings.
			 */

			// antipattern
			// appending inside
			$.each(reallyLongArray, function (count, item) {
				var newLI = '<li>' + item + '</li>';
				$('#ballers').append(newLI);
			});


			// documentFragment off-DOM
			var frag = document.createDocumentFragment();
			$.each(reallyLongArray, function (count, item) {
				var newLI = $('<li>' + item + '</li>');
				frag.appendChild(newLI[0]);
			});
			$('#ballers')[0].appendChild(frag);


			// string concatenate and set innerHTML
			var myhtml = '';
			$.each(reallyLongArray, function (count, item) {
				myhtml += '<li>' + item + '</li>';
			});
			$('#ballers').html(myhtml);

			// concatenate very long strings
			var myHtmlBuffer = [];
			$.each(reallyLongArray, function(count, item) {
				myHtmlBuffer.push('<li>' + item + '</li>');
			});
			$('#ballers').html(myHtmlBuffer.join(''));

			// References
			// http://paulirish.com/2009/perf/
			// http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/
			// http://stackoverflow.com/questions/112158/javascript-string-concatenation
			// http://stackoverflow.com/questions/153381/javascript-string-concatenation-faster-than-this-example
		</script>
	</body>
</html>


================================================
FILE: jquery-patterns/cache-selector.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: selector cache
			 Description: using selector cache to avoid requery
			 */

			// antipattern
			$('.list-item').click(function () {
				$('.photo').hide();
			});


			// preferred
			var $photo;
			// prefix the cache with $ to help identify it as a selector cache later
			$('.list-item').click(function () {
				$photo = $photo || $('.photo');
				$photo.hide();
			});


			// References
			// http://ejohn.org/blog/learning-from-twitter/
		</script>
	</body>
</html>


================================================
FILE: jquery-patterns/context-and-find.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: context and find
			 * Description: better to choose `find` over `context` 
			 */

			
			var arms = $('div.robotarm', '#container');
			$('.reply_form', $(this).closest('.comment')).hide();

			// no performance gain over doing this, but a preferred pattern for readability reason
			var arms = $('#container').find('div.robotarm');
			$(this).closest('.comment').find('.reply_form').hide();
			

			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/data.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: data
			 * Description: pattern and antipattern of using data
			 */

			// antipattern
			$(elem).data(key, value);


			// preferred
			$.data(elem, key, value);


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/decending-from-id.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Decending from id
			 * Description: be more specific, better to descend from an id
			 */

			// antipattern
			var arms = $('.container div.robotarm');


			// better
			var arms = $('#container div.robotarm');


			// preferred
			var arms = $('#container').find('div.robotarm');


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/detach.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: detach
			 * Description: take element off the DOM while manipulating them
			 */

			var table = $('#some-table');
			var parent = table.parent();

			table.detach();
			table.addLotsAndLotsOfRows();
			parent.append(table);


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/event-delegation.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: event delegation
			 Description: event delegation pattern and antipattern
			 */

			// antipattern 
			// As of jQuery 1.7, the .live() method is deprecated
			// $('a.trigger', $('#container')[0]).live('click', handlerFn);


			// preferred
			$('#container').on('click', 'a.trigger', handlerFn);

			// .bind()
			// .live() - best used for simple scenario, it functions the best with a supply selector only, it's not chainable
			// .delegate() - it gives you a more focused way, it can better filter the elements, for example, table row


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/left-and-right.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Left and Right
			 * Description: specific on the right, light on the left
			 */

			// antipattern
			$('div.data .brad')


			// preferred
			$('.data td.brad')


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/pubsub-callback.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
		<script>
			/* Title: Using jQuery 1.7's $.Callbacks() feature
			 * Description: $.Callbacks are a multi-purpose callbacks list object which can be used as a base layer to build new functionality including simple publish/subscribe systems. We haven't yet released the API documentation for this feature just yet, more information on it (including lots of examples) here: http://addyosmani.com/blog/jquery-1-7s-callbacks-feature-demystified/.
			 */

			var topics = {};

			jQuery.Topic = function( id ) {
			    var callbacks,
			        topic = id && topics[ id ];
			    if ( !topic ) {
			        callbacks = jQuery.Callbacks();
			        topic = {
			            publish: callbacks.fire,
			            subscribe: callbacks.add,
			            unsubscribe: callbacks.remove
			        };
			        if ( id ) {
			            topics[ id ] = topic;
			        }
			    }
			    return topic;
			};

			function fn1( value ){
				console.log( value );
			}

			function fn2( value ){
				fn1("fn2 says:" + value);
				return false;
			}

			// Usage:
			// Subscribers
			$.Topic( 'mailArrived' ).subscribe( fn1 );
			$.Topic( 'mailArrived' ).subscribe( fn2 );
			$.Topic( 'mailSent' ).subscribe( fn1 );

			// Publisher
			$.Topic( 'mailArrived' ).publish( 'hello world!' );
			$.Topic( 'mailSent' ).publish( 'woo! mail!' );

			//  Here, 'hello world!' gets pushed to fn1 and fn2
			//  when the 'mailArrived' notification is published
			//  with 'woo! mail!' also being pushed to fn1 when
			//  the 'mailSent' notification is published.
			/*
			output:
			hello world!
			fn2 says: hello world!
			woo! mail!
			*/

			// References
			// https://gist.github.com/1321768
		</script>
	</body>
</html>


================================================
FILE: jquery-patterns/pubsub-custom-events.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
		<script>
			/* Title: Custom events using .on() and .off()
			 * Description: A really tiny pub/sub implementation for jQuery 1.7 using the two new methods(since jQuery 1.7): .on() and .off().
			 */

			/* jQuery Tiny Pub/Sub - v0.7 - 10/27/2011
			 * http://benalman.com/
			 * Copyright (c) 2011 "Cowboy" Ben Alman; Licensed MIT, GPL */

			(function($) {

			  var o = $({});

			  $.subscribe = function() {
			    o.on.apply(o, arguments);
			  };

			  $.unsubscribe = function() {
			    o.off.apply(o, arguments);
			  };

			  $.publish = function() {
			    o.trigger.apply(o, arguments);
			  };

			}(jQuery));


			// Usage:
			// Super-basic example:

			function handle(e, a, b, c) {
			  // `e` is the event object, you probably don't care about it.
			  console.log(a + b + c);
			};

			$.subscribe("/some/topic", handle);

			$.publish("/some/topic", [ "a", "b", "c" ]);
			// logs: abc

			$.unsubscribe("/some/topic", handle); // Unsubscribe just this handler

			// Or:

			$.subscribe("/some/topic", function(e, a, b, c) {
			  console.log(a + b + c);
			});

			$.publish("/some/topic", [ "a", "b", "c" ]);
			// logs: abc
			// Unsubscribe all handlers for this topic
			$.unsubscribe("/some/topic"); 

			// References
			// https://gist.github.com/1321768
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/pubsub-observable.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="http://brado23.github.com/jquery-ui/jquery-1.6.2.js"></script>
    <script src="http://brado23.github.com/jquery-ui/ui/jquery.ui.core.js"></script>
    <script src="http://brado23.github.com/jquery-ui/ui/jquery.ui.widget.js"></script>
    <script src="http://brado23.github.com/jquery-ui/ui/jquery.ui.button.js"></script>
    <script src="http://brado23.github.com/jquery-ui/ui/jquery.ui.observable.js"></script>
    <script src="http://brado23.github.com/jquery-ui/grid-editing/localstore.js"></script>
		<script src="http://brado23.github.com/jquery-ui/grid-editing/observer.js"></script>​
		<script>
			/* Title: Using jQuery UI $.Observable
			 * Description: Using jQuery UI $.Observable (which is currently still under development), when objects/collections of data are changed or updated, events are triggered to inform any observers of the change
			 */

			/*$.observers example by @addyosmani*/

			var myData = [], 
			    observer = $.observer(myData);

			function dataChange( data ){
			   console.log('New data arrived with ID ' + data[0].id + ' and value ' + data[0].title);   
			}

			$(observer).bind("change", function ( e ) { 
			    dataChange( e.target.data );
			});

			$.observable( myData ).insert({
			                id: myData.length + 1,
			                title: 'test'
			            });
			
			// References
			// https://gist.github.com/1321768
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/pubsub-plugin.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
		<script>
			/* Title: One of the many third-party plugins
			 * Description: Peter Higgin's jQuery plugin, available here: https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
			 */


			;(function(d){
			    // the topic/subscription hash
			    var cache = {};

			    // Publish some data on a named topic.
			    d.publish = function(/* String */topic, /* Array? */args){
			        // topic: String - The channel to publish on
			        // args: Array - The data to publish. Each array item is converted into an ordered
			        // arguments on the subscribed functions. 
			        cache[topic] && d.each(cache[topic], function(){
			            this.apply(d, args || []);
			        });
			    };

			    // Register a callback on a named topic.
			    d.subscribe = function(/* String */topic, /* Function */callback){    
			        // @topic: String - The channel to subscribe to
			        // @callback: Function - The handler event. Anytime something is $.publish'ed on a 
			        // subscribed channel, the callback will be called with the published array as 
			        // ordered arguments.
			        //
			        // returns: Array - A handle which can be used to unsubscribe this 
			        // particular subscription.

			        if(!cache[topic]){
			            cache[topic] = [];
			        }
			        cache[topic].push(callback);
			        return [topic, callback]; // Array
			    };

			    // Disconnect a subscribed function for a topic.
			    d.unsubscribe = function(/* Array */handle){    
			        // handle: Array - The return value from a $.subscribe call.
			        var t = handle[0];
			        cache[t] && d.each(cache[t], function(idx){
			            if(this == handle[1]){
			                cache[t].splice(idx, 1);
			            }
			        });
			    };

			})(jQuery);


			// Usage:
			// Publish stuff on '/some/topic'. Anything subscribed will be called
			// with a function signature like: function(a,b,c){ ... }


			$.subscribe("/some/topic", function(a, b, c){ 
			    console.log(a,b,c);
			});


			$.publish("/some/topic", ["a","b","c"]);

			// References
			// https://gist.github.com/1321768
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/requery.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: requery
			 * Description: avoid requery by using jQuery chaining
			 */

			// antipattern
			// create and append your element
			$(document.body).append("<div class='baaron' />");
				// requery to bind stuff
				$("div.baaron").click(function () {
			});


			// preferred 1
			// swap to appendTo to hold your element
			$("<div class='baaron' />")
				.appendTo(document.body)
				.click(function () {
					// do stuff
				});
					
			// preferred 2
			// cache the selector
			var $baaron = $("<div class='baaron' />").appendTo(document.body);
			
			$baaron.click(function () {
				// do stuff
			});


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>


================================================
FILE: jquery-patterns/specific-when-needed.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Be Specific when Needed
			 * Description: no need to be over-specific
			 */

			// antipattern
			var arms = $('.data table.attendees td.brad');


			// preferred
			var arms = $('.data td.brad');


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/universal-selector.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: Universal Selector
			 * Description: better use of universal selector
			 */

			// antipattern 1
			$('.buttons > *')


			// preferred 1
			$('.buttons').children()


			// antipattern 2
			$('.gender :radio')
			$('.gender *:radio')


			// preferred 2
			$('.gender input:radio')


			// References
			// http://paulirish.com/2009/perf/
		</script>
	</body>
</html>

================================================
FILE: jquery-patterns/window-scroll-event.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
			/* Title: window scroll event
			 * Description: avoid attaching handlers to the window scroll event
			 */

			// antipattern
			$(window).scroll(function () {
				$('.foo').something();
			});


			// preferred
			var outerPane = $details.find(".details-pane-outer"),
					didScroll = false;
			$(window).scroll(function () {
				didScroll = true;
			});

			setInterval(function () {
				if (didScroll) {
					didScroll = false;
					// Check your page position and then
					// Load in more results
					// outerPane.html();
				}
			}, 250);


			// preferred v2, timeout instead of interval - no unnecessary ticks
			var scrollTimeout;  // global for any pending scrollTimeout
			var outerPane = $details.find(".details-pane-outer");

			$(window).scroll(function () {
				if (scrollTimeout) {
					// clear the timeout, if one is pending
					clearTimeout(scrollTimeout);
					scrollTimeout = null;
				}
				scrollTimeout = setTimeout(scrollHandler, 250);
			});

			scrollHandler = function () {
				// Check your page position and then
				// Load in more results
				// outerPane.html();
			};


			// References
			// http://ejohn.org/blog/learning-from-twitter/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/amd-commonjs/pluginCore.js
================================================
// Module/Plugin core
// Note: the wrapper code you see around the module is what enables
// us to support multiple module formats and specifications by
// mapping the arguments defined to what a specific format expects
// to be present. Our actual module functionality is defined lower
// down, where a named module and exports are demonstrated.
//
// Note that dependencies can just as easily be declared if required
// and should work as demonstrated earlier with the AMD module examples.

(function ( name, definition ){
  var theModule = definition(),
      // this is considered "safe":
      hasDefine = typeof define === 'function' && define.amd,
      // hasDefine = typeof define === 'function',
      hasExports = typeof module !== 'undefined' && module.exports;

  if ( hasDefine ){ // AMD Module
    define(theModule);
  } else if ( hasExports ) { // Node.js Module
    module.exports = theModule;
  } else { // Assign to common namespaces or simply the global object (window)
    (this.jQuery || this.ender || this.$ || this)[name] = theModule;
  }
})( 'core', function () {
    var module = this;
    module.plugins = [];
    module.highlightColor = "yellow";
    module.errorColor = "red";

  // define the core module here and return the public API

  // This is the highlight method used by the core highlightAll()
  // method and all of the plugins highlighting elements different
  // colors
  module.highlight = function(el,strColor){
    if(this.jQuery){
      jQuery(el).css('background', strColor);
    }
  }
  return {
      highlightAll:function(){
        module.highlight('div', module.highlightColor);
      }
  };

});

================================================
FILE: jquery-plugin-patterns/amd-commonjs/pluginExtension.js
================================================
// Extension to module core

(function ( name, definition ) {
    var theModule = definition(),
        hasDefine = typeof define === 'function',
        hasExports = typeof module !== 'undefined' && module.exports;

    if ( hasDefine ) { // AMD Module
        define(theModule);
    } else if ( hasExports ) { // Node.js Module
        module.exports = theModule;
    } else { // Assign to common namespaces or simply the global object (window)

        // account for for flat-file/global module extensions
        var obj = null;
        var namespaces = name.split(".");
        var scope = (this.jQuery || this.ender || this.$ || this);
        for (var i = 0; i < namespaces.length; i++) {
            var packageName = namespaces[i];
            if (obj && i == namespaces.length - 1) {
                obj[packageName] = theModule;
            } else if (typeof scope[packageName] === "undefined") {
                scope[packageName] = {};
            }
            obj = scope[packageName];
        }

    }
})('core.plugin', function () {

    // Define your module here and return the public API.
    // This code could be easily adapted with the core to
    // allow for methods that overwrite and extend core functionality
    // in order to expand the highlight method to do more if you wish.
    return {
        setGreen: function ( el ) {
            highlight(el, 'green');
        },
        setRed: function ( el ) {
            highlight(el, errorColor);
        }
    };

});

================================================
FILE: jquery-plugin-patterns/amd-commonjs/usage.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script src="pluginCore.js"></script>
		<script src="pluginExtension.js"></script>

		<script type="text/javascript">

		$(function(){

		    // Our plugin 'core' is exposed under a core namespace in
		    // this example, which we first cache
		    var core = $.core;

		    // Then use use some of the built-in core functionality to
		    // highlight all divs in the page yellow
		    core.highlightAll();

		    // Access the plugins (extensions) loaded into the 'plugin'
		    // namespace of our core module:

		    // Set the first div in the page to have a green background.
		    core.plugin.setGreen("div:first");
		    // Here we're making use of the core's 'highlight' method
		    // under the hood from a plugin loaded in after it

		    // Set the last div to the 'errorColor' property defined in
		    // our core module/plugin. If you review the code further down,
		    // you'll see how easy it is to consume properties and methods
		    // between the core and other plugins
		    core.plugin.setRed('div:last');
		});

		</script>
		
		<script>
		// References
		// http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/basic.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script>
		/*!
		 * jQuery basic plugin boilerplate
		 */

		/*
		The most basic form of jQuery plugin
		This is great for compactness
		*/

		$.fn.myPluginName = function() {
		    // your plugin logic
		};


		/*
		A better foundation to build on
		Here, we’ve wrapped our plugin logic in an anonymous function. To ensure that our use of the $ sign as a shorthand creates no conflicts between jQuery and other JavaScript libraries, we simply pass it to this closure, which maps it to the dollar sign, thus ensuring that it can’t be affected by anything outside of its scope of execution.
		*/

		(function( $ ){
		  	$.fn.myPluginName = function() {
		    	// your plugin logic
		  	};
		})( jQuery );


		// References
		// Essential jQuery Plugin Patterns (by Addy Osmani) - http://goo.gl/oE0ge
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/best-options.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
		/*!
		 * jQuery 'best options' plugin boilerplate
		 * Author: @cowboy
		 * Further changes: @addyosmani
		 * Licensed under the MIT license
		 */

		;(function ( $, window, document, undefined ) {

		    $.fn.pluginName = function ( options ) {

		        // Here's a best practice for overriding 'defaults'
		        // with specified options. Note how, rather than a
		        // regular defaults object being passed as the second
		        // parameter, we instead refer to $.fn.pluginName.options
		        // explicitly, merging it with the options passed directly
		        // to the plugin. This allows us to override options both
		        // globally and on a per-call level. 

		        options = $.extend( {}, $.fn.pluginName.options, options );

		        return this.each(function () {

		            var elem = $(this);

		        });
		    };

		    // Globally overriding options
		    // Here are our publicly accessible default plugin options
		    // that are available in case the user doesn't pass in all
		    // of the values expected. The user is given a default
		    // experience but can also override the values as necessary.
		    // eg. $fn.pluginName.key ='otherval';

		    $.fn.pluginName.options = {

		        key: "value",
		        myMethod: function ( elem, param ) {

		        }
		    };

		})( jQuery, window, document );


		// References
		/*
		jQuery Pluginization and the accompanying gist (by Ben Alman) - http://goo.gl/1VwfP http://goo.gl/bg63
		Essential jQuery Plugin Patterns (by Addy Osmani) - http://goo.gl/oE0ge
		*/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/custom-events.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
		/*!
		 * jQuery custom-events plugin boilerplate
		 * Author: DevPatch
		 * Further changes: @addyosmani
		 * Licensed under the MIT license
		 */

		// In this pattern, we use jQuery's custom events to add
		// pub/sub (publish/subscribe) capabilities to widgets.
		// Each widget would publish certain events and subscribe
		// to others. This approach effectively helps to decouple
		// the widgets and enables them to function independently.

		;(function ( $, window, document, undefined ) {
		    $.widget("ao.eventStatus", {
		        options: {

		        },

		        _create : function() {
		            var self = this;

		            //self.element.addClass( "my-widget" );

		            //subscribe to 'myEventStart'
		            self.element.bind( "myEventStart", function( e ) {
		                console.log("event start");
		            });

		            //subscribe to 'myEventEnd'
		            self.element.bind( "myEventEnd", function( e ) {
		                console.log("event end");
		            });

		            //unsubscribe to 'myEventStart'
		            //self.element.unbind( "myEventStart", function(e){
		                ///console.log("unsubscribed to this event");
		            //});
		        },

		        destroy: function(){
		            $.Widget.prototype.destroy.apply( this, arguments );
		        },
		    });
		})( jQuery, window , document );

		//Publishing event notifications
		//usage:
		// $(".my-widget").trigger("myEventStart");
		// $(".my-widget").trigger("myEventEnd");


		// References
		/*
		Communication Between jQuery UI Widgets (by Benjamin Sternthal) - http://goo.gl/oE0ge
		Understanding the Publish/Subscribe Pattern for Greater JavaScript Scalability (by Addy Osmani) - http://goo.gl/CU5fC
		Essential jQuery Plugin Patterns (by Addy Osmani) - http://goo.gl/oE0ge
		*/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/extend.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
		/*!
		 * jQuery extend-based plugin boilerplate
		 * Author: @oscargodson
		 * Further changes: @timmywil
		 * Licensed under the MIT license
		 */

		/*
		As you'll notice below, we're making use of $.fn.extend to create our plugin rather
		than opting for $.fn.pluginname. This type of structure may be useful if you need
		to add a relatively large number of methods to your plugin. There are however alternatives
		to this that may be better suited, including Alex Sexton's prototypal inheritence pattern
		which is also included in this repo.
		*/


		// the semi colon before function invocation is a safety net against concatenated
		// scripts and/or other plugins which may not be closed properly.
		;( function( $ ){
			$.fn.extend( {
				pluginname: function( options ) {

					this.defaults = {};

					var settings = $.extend( {}, this.defaults, options );

					return this.each( function() {

						var $this = $( this );

					});

				}

			});

		})( jQuery );


		// References
		// Essential jQuery Plugin Patterns (by Addy Osmani) - http://goo.gl/oE0ge
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/highly-configurable-mutable.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
		/*
		 * 'Highly configurable' mutable plugin boilerplate
		 * Author: @markdalgleish
		 * Further changes, comments: @addyosmani
		 * Licensed under the MIT license
		 */

		// Note that with this pattern, as per Alex Sexton's, the plugin logic
		// hasn't been nested in a jQuery plugin. Instead, we just use
		// jQuery for its instantiation.

		;(function( $, window, document, undefined ){

		  // our plugin constructor
		  var Plugin = function( elem, options ){
		      this.elem = elem;
		      this.$elem = $(elem);
		      this.options = options;

		      // This next line takes advantage of HTML5 data attributes
		      // to support customization of the plugin on a per-element
		      // basis. For example,
		      // <div class=item' data-plugin-options='{"message":"Goodbye World!"}'></div>
		      this.metadata = this.$elem.data( 'plugin-options' );
		    };

		  // the plugin prototype
		  Plugin.prototype = {
		    defaults: {
		      message: 'Hello world!'
		    },

		    init: function() {
		      // Introduce defaults that can be extended either
		      // globally or using an object literal.
		      this.config = $.extend({}, this.defaults, this.options,
		      this.metadata);

		      // Sample usage:
		      // Set the message per instance:
		      // $('#elem').plugin({ message: 'Goodbye World!'});
		      // or
		      // var p = new Plugin(document.getElementById('elem'),
		      // { message: 'Goodbye World!'}).init()
		      // or, set the global default message:
		      // Plugin.defaults.message = 'Goodbye World!'

		      this.sampleMethod();
		      return this;
		    },

		    sampleMethod: function() {
		      // eg. show the currently configured message
		      // console.log(this.config.message);
		    }
		  }

		  Plugin.defaults = Plugin.prototype.defaults;

		  $.fn.plugin = function(options) {
		    return this.each(function() {
		      new Plugin(this, options).init();
		    });
		  };

		  //optional: window.Plugin = Plugin;

		})( jQuery, window , document );


		// References
		/*
		Creating Highly Configurable jQuery Plugins (by Mark Dalgleish) - http://goo.gl/1VwfP http://goo.gl/bg63
		Essential jQuery Plugin Patterns (by Addy Osmani) - http://goo.gl/oE0ge
		*/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/jquery-mobile-ui-widget-factory.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script>
		/*!
		 * (jQuery mobile) jQuery UI Widget-factory plugin boilerplate (for 1.8/9+)
		 * Author: @scottjehl
		 * Further changes: @addyosmani
		 * Licensed under the MIT license
		 */

		;(function ( $, window, document, undefined ) {

		    //define a widget under a namespace of your choice
		    //here 'mobile' has been used in the first parameter
		    $.widget( "mobile.widgetName", $.mobile.widget, {

		        //Options to be used as defaults
		        options: {
		            foo: true,
		            bar: false
		        },

		        _create: function() {
		            // _create will automatically run the first time this
		            // widget is called. Put the initial widget set-up code
		            // here, then you can access the element on which
		            // the widget was called via this.element
		            // The options defined above can be accessed via
		            // this.options

		            //var m = this.element,
		            //p = m.parents(":jqmData(role='page')"),
		            //c = p.find(":jqmData(role='content')")
		        },

		        // Private methods/props start with underscores
		        _dosomething: function(){ ... },

		        // Public methods like these below can can be called
		                // externally:
		        // $("#myelem").foo( "enable", arguments );

		        enable: function() { ... },

		        // Destroy an instantiated plugin and clean up modifications
		        // the widget has made to the DOM
		        destroy: function () {
		            //this.element.removeStuff();
		            // For UI 1.8, destroy must be invoked from the
		            // base widget
		            $.Widget.prototype.destroy.call(this);
		            // For UI 1.9, define _destroy instead and don't
		            // worry about calling the base widget
		        },

		        methodB: function ( event ) {
		            //_trigger dispatches callbacks the plugin user can
		            // subscribe to
		            //signature: _trigger( "callbackName" , [eventObject],
		            //  [uiObject] )
		            // eg. this._trigger( "hover", e /*where e.type ==
		            // "mouseenter"*/, { hovered: $(e.target)});
		            this._trigger('methodA', event, {
		                key: value
		            });
		        },

		        methodA: function ( event ) {
		            this._trigger('dataChanged', event, {
		                key: value
		            });
		        },

		        //Respond to any changes the user makes to the option method
		        _setOption: function ( key, value ) {
		            switch (key) {
		            case "someValue":
		                //this.options.someValue = doSomethingWith( value );
		                break;
		            default:
		                //this.options[ key ] = value;
		                break;
		            }

		            // For UI 1.8, _setOption must be manually invoked from
		            // the base widget
		            $.Widget.prototype._setOption.apply(this, arguments);
		            // For UI 1.9 the _super method can be used instead
		            // this._super( "_setOption", key, value );
		        }
		    });

		})( jQuery, window, document );

		//usage: $("#myelem").foo( options );

		/* Some additional notes - delete this section before using the boilerplate.

		 We can also self-init this widget whenever a new page in jQuery Mobile is created. jQuery Mobile's "page" plugin dispatches a "create" event when a jQuery Mobile page (found via data-role=page attr) is first initialized.

		We can listen for that event (called "pagecreate" ) and run our plugin automatically whenever a new page is created.

		$(document).bind("pagecreate", function (e) {
		    // In here, e.target refers to the page that was created
		    // (it's the target of the pagecreate event)
		    // So, we can simply find elements on this page that match a
		    // selector of our choosing, and call our plugin on them.
		    // Here's how we'd call our "foo" plugin on any element with a
		    // data-role attribute of "foo":
		    $(e.target).find("[data-role='foo']").foo(options);

		    // Or, better yet, let's write the selector accounting for the configurable
		    // data-attribute namespace
		    $(e.target).find(":jqmData(role='foo')").foo(options);
		});

		That's it. Now you can simply reference the script containing your widget and pagecreate binding in a page running jQuery Mobile site, and it will automatically run like any other jQM plugin.
		*/


		// References
		// http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
		</script>
	</body>
</html>

================================================
FILE: jquery-plugin-patterns/lightweight.html
================================================
<!doctype html>
<html lang="en">
	<head>
		<title>JavaScript Patterns</title>
		<meta charset="utf-8">
	</head>
	<body>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script>
		/*!
		 * jQuery lightweight plugin boilerplate
		 * Original author: @ajpiano
		 * Further changes, comments: @addyosmani
		 * Licensed under the MIT license
		 */

		// the semi-colon before the function invocation is a safety
		// net against concatenated scripts and/or other plugins
		// that are not closed properly.
		;(function ( $, window, document, undefined ) {

		    // undefined is used here as the undefined global
		    // variable in ECMAScript 3 and is mutable (i.e. it can
		    // be changed by someone else). undefined isn't really
		    // being passed in so we can ensure that its value is
		    // truly undefined. In ES5, undefined can no longer be
		    // modified.

		    // window and document are passed through as local
		  
Download .txt
gitextract_ubd058uh/

├── README.md
├── cn/
│   └── index.html
├── code-reuse-patterns/
│   ├── borrowing-methods.html
│   ├── cp1-default.html
│   ├── cp2-rent-a-constructor.html
│   ├── cp3-rent-and-set-prototype.html
│   ├── cp4-share-the-prototype.html
│   ├── cp5-a-temporary-constructor.html
│   ├── inheritance-by-copying-properties.html
│   ├── klass.html
│   ├── mix-ins.html
│   └── prototypal-inheritance.html
├── css/
│   └── style.css
├── design-patterns/
│   ├── builder.html
│   ├── chain-of-responsibility.html
│   ├── command.html
│   ├── decorator.html
│   ├── facade.html
│   ├── factory.html
│   ├── iterator.html
│   ├── mediator.html
│   ├── multiton.html
│   ├── observer.html
│   ├── proxy.html
│   ├── singleton.html
│   ├── strategy.html
│   └── visitor.html
├── dom-and-browser/
│   └── event-handling.html
├── function-patterns/
│   ├── callback.html
│   ├── callbacks-and-scope.html
│   ├── configuration-objects.html
│   ├── currying.html
│   ├── enforcing-new-in-constructors.html
│   ├── function-call.html
│   ├── immediate-functions.html
│   ├── immediate-object-initialization.html
│   ├── init-time-branching.html
│   ├── memoization.html
│   ├── partial-application.html
│   ├── returning-functions.html
│   ├── self-defining-functions.html
│   └── self-overwrite.html
├── general-patterns/
│   ├── access-to-global-object.html
│   ├── avoiding-eval.html
│   ├── avoiding-implied-typecasting.html
│   ├── built-in-prototypes.html
│   ├── conditionals.html
│   ├── for-in-loops.html
│   ├── for-loops.html
│   ├── function-declarations.html
│   ├── global-import.html
│   ├── globals.html
│   ├── hoisting.html
│   ├── iife-for-loop.html
│   ├── map-and-filter-by-reduce.html
│   ├── minimizing-globals.html
│   ├── parseint.html
│   ├── shim-sniffing.html
│   ├── single-var-pattern.html
│   └── switch-pattern.html
├── img/
│   └── .gitignore
├── index.html
├── jquery-patterns/
│   ├── append.html
│   ├── cache-selector.html
│   ├── context-and-find.html
│   ├── data.html
│   ├── decending-from-id.html
│   ├── detach.html
│   ├── event-delegation.html
│   ├── left-and-right.html
│   ├── pubsub-callback.html
│   ├── pubsub-custom-events.html
│   ├── pubsub-observable.html
│   ├── pubsub-plugin.html
│   ├── requery.html
│   ├── specific-when-needed.html
│   ├── universal-selector.html
│   └── window-scroll-event.html
├── jquery-plugin-patterns/
│   ├── amd-commonjs/
│   │   ├── pluginCore.js
│   │   ├── pluginExtension.js
│   │   └── usage.html
│   ├── basic.html
│   ├── best-options.html
│   ├── custom-events.html
│   ├── extend.html
│   ├── highly-configurable-mutable.html
│   ├── jquery-mobile-ui-widget-factory.html
│   ├── lightweight.html
│   ├── namespaced-starter.html
│   ├── prototypal-inheritance.html
│   ├── ui-widget-factory-bridge.html
│   ├── ui-widget-factory-mobile.html
│   ├── ui-widget-factory.html
│   └── ui-widget-requirejs-module.html
├── js/
│   ├── libs/
│   │   └── jquery-1.6.4.js
│   ├── plugins.js
│   └── script.js
├── literals-and-constructors/
│   ├── array-literal.html
│   ├── enforcing-new.html
│   ├── json.html
│   ├── object-literal.html
│   ├── primitive-wrappers.html
│   └── regular-expression-literal.html
└── object-creation-patterns/
    ├── chaining.html
    ├── declaring-dependencies.html
    ├── inheritence.html
    ├── module.html
    ├── module2.html
    ├── module3-augmentation.html
    ├── module4-loose-augmentation.html
    ├── module5-tight-augmentation.html
    ├── module6-clone-inheritance.html
    ├── module7-cross-file.html
    ├── namespace.html
    ├── object-constants.html
    ├── private-properties-and-methods.html
    ├── revelation.html
    ├── sandbox.html
    ├── static-members.html
    ├── sub-module.html
    └── sugar-method.html
Download .txt
SYMBOL INDEX (41 symbols across 2 files)

FILE: js/libs/jquery-1.6.4.js
  function jQuerySub (line 871) | function jQuerySub( selector, context ) {
  function doScrollCheck (line 937) | function doScrollCheck() {
  function resolveFunc (line 1127) | function resolveFunc( i ) {
  function dataAttr (line 1728) | function dataAttr( elem, key, data ) {
  function isEmptyDataObject (line 1761) | function isEmptyDataObject( obj ) {
  function handleQueueMarkDefer (line 1774) | function handleQueueMarkDefer( elem, type, src ) {
  function resolve (line 1924) | function resolve() {
  function returnFalse (line 3169) | function returnFalse() {
  function returnTrue (line 3172) | function returnTrue() {
  function trigger (line 3416) | function trigger( type, elem, args ) {
  function handler (line 3451) | function handler( donor ) {
  function liveHandler (line 3655) | function liveHandler( event ) {
  function liveConvert (line 3743) | function liveConvert( type, selector ) {
  function dirNodeCheck (line 5058) | function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  function dirCheck (line 5091) | function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  function isDisconnected (line 5371) | function isDisconnected( node ) {
  function winnow (line 5493) | function winnow( elements, qualifier, keep ) {
  function root (line 5873) | function root( elem, cur ) {
  function cloneCopyEvent (line 5880) | function cloneCopyEvent( src, dest ) {
  function cloneFixAttributes (line 5909) | function cloneFixAttributes( src, dest ) {
  function getAll (line 6041) | function getAll( elem ) {
  function fixDefaultChecked (line 6054) | function fixDefaultChecked( elem ) {
  function findInputs (line 6060) | function findInputs( elem ) {
  function evalScript (line 6279) | function evalScript( i, elem ) {
  function getWH (line 6617) | function getWH( elem, name, extra ) {
  function addToPrefiltersOrTransports (line 6743) | function addToPrefiltersOrTransports( structure ) {
  function inspectPrefiltersOrTransports (line 6779) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
  function ajaxExtend (line 6821) | function ajaxExtend( target, src ) {
  function done (line 7163) | function done( status, nativeStatusText, responses, headers ) {
  function buildParams (line 7478) | function buildParams( prefix, obj, traditional, add ) {
  function ajaxHandleResponses (line 7528) | function ajaxHandleResponses( s, jqXHR, responses ) {
  function ajaxConvert (line 7593) | function ajaxConvert( s, response ) {
  function createStandardXHR (line 7859) | function createStandardXHR() {
  function createActiveXHR (line 7865) | function createActiveXHR() {
  function createFxNow (line 8344) | function createFxNow() {
  function clearFxNow (line 8349) | function clearFxNow() {
  function genFx (line 8354) | function genFx( type, num ) {
  function t (line 8464) | function t( gotoEnd ) {
  function defaultDisplay (line 8619) | function defaultDisplay( nodeName ) {
  function getWindow (line 8965) | function getWindow( elem ) {

FILE: js/plugins.js
  function c (line 15) | function c(){}
Condensed preview — 121 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (545K chars).
[
  {
    "path": "README.md",
    "chars": 287,
    "preview": "#JavaScript Patterns\n\n<img src=\"http://shichuan.github.io/javascript-patterns/img/js-patterns.png\" alt=\"JS Patterns\" tit"
  },
  {
    "path": "cn/index.html",
    "chars": 19096,
    "preview": "<!doctype html>\r\n<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->\r\n<!--[if lt IE 7]> <h"
  },
  {
    "path": "code-reuse-patterns/borrowing-methods.html",
    "chars": 2043,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/cp1-default.html",
    "chars": 1224,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/cp2-rent-a-constructor.html",
    "chars": 1303,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/cp3-rent-and-set-prototype.html",
    "chars": 1130,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/cp4-share-the-prototype.html",
    "chars": 1032,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/cp5-a-temporary-constructor.html",
    "chars": 1813,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/inheritance-by-copying-properties.html",
    "chars": 1670,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/klass.html",
    "chars": 3740,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/mix-ins.html",
    "chars": 866,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "code-reuse-patterns/prototypal-inheritance.html",
    "chars": 1698,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "css/style.css",
    "chars": 13075,
    "preview": "/*\r\n * HTML5 ✰ Boilerplate\r\n *\r\n * What follows is the result of much research on cross-browser styling.\r\n * Credit left"
  },
  {
    "path": "design-patterns/builder.html",
    "chars": 984,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <title>JavaScript Patterns</title>\n    <meta charset=\"utf-8\">\n  </head>\n  "
  },
  {
    "path": "design-patterns/chain-of-responsibility.html",
    "chars": 1246,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/command.html",
    "chars": 1142,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/decorator.html",
    "chars": 1314,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/facade.html",
    "chars": 586,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/factory.html",
    "chars": 2017,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/iterator.html",
    "chars": 1528,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <title>JavaScript Patterns</title>\n    <meta charset=\"utf-8\">\n  </head>\n "
  },
  {
    "path": "design-patterns/mediator.html",
    "chars": 1954,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/multiton.html",
    "chars": 1837,
    "preview": "<!doctype html>\n<html lang=\"en\">\n<head>\n<title>JavaScript Patterns</title>\n<meta charset=\"utf-8\">\n</head>\n<body>\n<script"
  },
  {
    "path": "design-patterns/observer.html",
    "chars": 1964,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/proxy.html",
    "chars": 5981,
    "preview": "<!doctype html>\n<html lang=\"en\">\n<head>\n\t<title>JavaScript Patterns</title>\n\t<meta charset=\"utf-8\">\n\t<style>\n\t\timg {\n\t\t"
  },
  {
    "path": "design-patterns/singleton.html",
    "chars": 2770,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "design-patterns/strategy.html",
    "chars": 2599,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "design-patterns/visitor.html",
    "chars": 1964,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "dom-and-browser/event-handling.html",
    "chars": 1516,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "function-patterns/callback.html",
    "chars": 1108,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/callbacks-and-scope.html",
    "chars": 853,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/configuration-objects.html",
    "chars": 516,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/currying.html",
    "chars": 4943,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/enforcing-new-in-constructors.html",
    "chars": 469,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/function-call.html",
    "chars": 1660,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <title>JavaScript Patterns</title>\n    <meta charset=\"utf-8\">\n  </head>\n  "
  },
  {
    "path": "function-patterns/immediate-functions.html",
    "chars": 789,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/immediate-object-initialization.html",
    "chars": 782,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/init-time-branching.html",
    "chars": 1620,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/memoization.html",
    "chars": 1964,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/partial-application.html",
    "chars": 2109,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/returning-functions.html",
    "chars": 1640,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/self-defining-functions.html",
    "chars": 1013,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "function-patterns/self-overwrite.html",
    "chars": 334,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/access-to-global-object.html",
    "chars": 617,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/avoiding-eval.html",
    "chars": 1020,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/avoiding-implied-typecasting.html",
    "chars": 1337,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/built-in-prototypes.html",
    "chars": 1318,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/conditionals.html",
    "chars": 2894,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/for-in-loops.html",
    "chars": 2095,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/for-loops.html",
    "chars": 1443,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "general-patterns/function-declarations.html",
    "chars": 1544,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/global-import.html",
    "chars": 489,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/globals.html",
    "chars": 1038,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/hoisting.html",
    "chars": 1258,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/iife-for-loop.html",
    "chars": 1213,
    "preview": "<!doctype html>\n<html lang=\"en\">\n    <head>\n        <title>JavaScript Patterns</title>\n        <meta charset=\"utf-8\">\n  "
  },
  {
    "path": "general-patterns/map-and-filter-by-reduce.html",
    "chars": 1035,
    "preview": "<!doctype html>\n<html lang=\"en\">\n<head>\n    <title>JavaScript Patterns</title>\n    <meta charset=\"utf-8\">\n</head>\n<body>"
  },
  {
    "path": "general-patterns/minimizing-globals.html",
    "chars": 855,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/parseint.html",
    "chars": 1693,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/shim-sniffing.html",
    "chars": 1758,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "general-patterns/single-var-pattern.html",
    "chars": 1446,
    "preview": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <title>JavaScript Patterns</title>\n    <meta charset=\"utf-8\">\n  </head>\n  "
  },
  {
    "path": "general-patterns/switch-pattern.html",
    "chars": 1761,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "img/.gitignore",
    "chars": 13,
    "preview": "!.gitignore\n\n"
  },
  {
    "path": "index.html",
    "chars": 29828,
    "preview": "<!doctype html>\r\n<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->\r\n<!--[if lt IE 7]> <h"
  },
  {
    "path": "jquery-patterns/append.html",
    "chars": 1503,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/cache-selector.html",
    "chars": 620,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/context-and-find.html",
    "chars": 626,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/data.html",
    "chars": 393,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/decending-from-id.html",
    "chars": 512,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/detach.html",
    "chars": 455,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/event-delegation.html",
    "chars": 772,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/left-and-right.html",
    "chars": 393,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/pubsub-callback.html",
    "chars": 1924,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/pubsub-custom-events.html",
    "chars": 1525,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/pubsub-observable.html",
    "chars": 1544,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/pubsub-plugin.html",
    "chars": 2428,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-patterns/requery.html",
    "chars": 840,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/specific-when-needed.html",
    "chars": 428,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/universal-selector.html",
    "chars": 514,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "jquery-patterns/window-scroll-event.html",
    "chars": 1338,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/amd-commonjs/pluginCore.js",
    "chars": 1649,
    "preview": "// Module/Plugin core\n// Note: the wrapper code you see around the module is what enables\n// us to support multiple mod"
  },
  {
    "path": "jquery-plugin-patterns/amd-commonjs/pluginExtension.js",
    "chars": 1500,
    "preview": "// Extension to module core\n\n(function ( name, definition ) {\n    var theModule = definition(),\n        hasDefine = typ"
  },
  {
    "path": "jquery-plugin-patterns/amd-commonjs/usage.html",
    "chars": 1409,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/basic.html",
    "chars": 1041,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/best-options.html",
    "chars": 1733,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/custom-events.html",
    "chars": 2005,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/extend.html",
    "chars": 1236,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/highly-configurable-mutable.html",
    "chars": 2403,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/jquery-mobile-ui-widget-factory.html",
    "chars": 4779,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/lightweight.html",
    "chars": 3152,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/namespaced-starter.html",
    "chars": 1875,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/prototypal-inheritance.html",
    "chars": 2652,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/ui-widget-factory-bridge.html",
    "chars": 3355,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/ui-widget-factory-mobile.html",
    "chars": 3808,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/ui-widget-factory.html",
    "chars": 3705,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "jquery-plugin-patterns/ui-widget-requirejs-module.html",
    "chars": 4120,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "js/libs/jquery-1.6.4.js",
    "chars": 238158,
    "preview": "/*!\n * jQuery JavaScript Library v1.6.4\n * http://jquery.com/\n *\n * Copyright 2011, John Resig\n * Dual licensed under th"
  },
  {
    "path": "js/plugins.js",
    "chars": 990,
    "preview": "\n// usage: log('inside coolFunc', this, arguments);\n// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/\nwind"
  },
  {
    "path": "js/script.js",
    "chars": 31,
    "preview": "/* Author:\n  Shi Chuan\n*/\n\n\n\n\n\n"
  },
  {
    "path": "literals-and-constructors/array-literal.html",
    "chars": 455,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "literals-and-constructors/enforcing-new.html",
    "chars": 1367,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "literals-and-constructors/json.html",
    "chars": 578,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "literals-and-constructors/object-literal.html",
    "chars": 468,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "literals-and-constructors/primitive-wrappers.html",
    "chars": 1278,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "literals-and-constructors/regular-expression-literal.html",
    "chars": 445,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/chaining.html",
    "chars": 689,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/declaring-dependencies.html",
    "chars": 482,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/inheritence.html",
    "chars": 6142,
    "preview": "<!--\n* One base class is created.\n* Another child class created extending the base class to demonstrate the inheritance."
  },
  {
    "path": "object-creation-patterns/module.html",
    "chars": 2794,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/module2.html",
    "chars": 1369,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/module3-augmentation.html",
    "chars": 572,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/module4-loose-augmentation.html",
    "chars": 611,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/module5-tight-augmentation.html",
    "chars": 746,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/module6-clone-inheritance.html",
    "chars": 923,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/module7-cross-file.html",
    "chars": 781,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/namespace.html",
    "chars": 1270,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/object-constants.html",
    "chars": 1418,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/private-properties-and-methods.html",
    "chars": 998,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/revelation.html",
    "chars": 1092,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/sandbox.html",
    "chars": 2325,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/static-members.html",
    "chars": 2747,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  },
  {
    "path": "object-creation-patterns/sub-module.html",
    "chars": 417,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>\n"
  },
  {
    "path": "object-creation-patterns/sugar-method.html",
    "chars": 813,
    "preview": "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<title>JavaScript Patterns</title>\n\t\t<meta charset=\"utf-8\">\n\t</head>\n\t<body>"
  }
]

About this extraction

This page contains the full source code of the chuanxshi/javascript-patterns GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 121 files (467.8 KB), approximately 134.7k tokens, and a symbol index with 41 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!