[
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "README.md",
    "content": "# 开发无框架单页面应用 -- 老码农的祖传秘方\n#\n\n## 什么是单页面应用（SPA）？\n[维基百科上的描述](http://en.wikipedia.org/wiki/Single-page_application )是这样的：\n```\n“A single-page application (SPA), is a web application or web site\nthat fits on a single web page with the goal of providing a more\nfluid user experience akin to a desktop application.”\n```\n也就是说，单页面应用是仅包含单个网页的应用，目的是为了提供类似于本地应用的流畅用户体验。\n\n## 需不需要框架？\n要实现单页面应用，现在已经有很多现成的框架了，比如`AngularJS`, `Ember.js`, `Backbone.js`等等。它们都是很全面的开发平台，为单页面应用开发提供了必需的页面模板、路径解析和处理、后台服务api访问、DOM操作等功能。\n\n事实上，现代的web应用开发基本都离不开一个甚至多个框架，开发无框架应用的想法听起来蛮不靠谱的，对吧？\n\n但是我总觉得现在是时候抛弃框架了。前两年我都在用 `AngularJS` 做开发，可以说已经比较熟悉它了，我的第一个单页面应用就是在 `AngularJS` 的启发下做出来的。框架曾经是我的挚爱。\n\n但是现在每次看着它们那庞大臃肿的身躯和晦涩的语法，我都有一种鸡肋的感觉。还有不同框架下各种工具、插件难以混用的现状，让我不得不经常需要自己写原生代码解决很多问题。时间长了，我自然冒出一个想法：“为啥不干脆抛弃框架，直接写原生代码呢？毕竟，框架也是原生代码写出来的嘛。”\n\n## 怎么实现无框架SPA？\n无框架单页面应用看似可行，但难度有多大？我还是心里没底，需要一点理论依据给自己壮胆。所以我就在网上到处寻摸了一番，偶然找到了这篇 Google 工程师 Joe Gregorio 写的文章[《别再用JS框架了》](http://coderlmn.github.io/frontEndCourse/nomoreJSF.html )，里面的分析有一种与我心有戚戚的感觉，看完还给它翻译成中文了。\n\n不过，他提出的方法是更超前的，例如 `imports` 和 `Polymer`，我曾经试过，印象中只有 Google 的 Chrome Canary 才有支持，而且要先在选项中打开一些试验功能，浏览器会变得不那么稳定。`X-Tag` 和 `Bosonic` 也要依赖于一个小的库。而我想做的是现在的浏览器就已经能支持的功能，用原生代码来实现。所以他这篇文章只能让我坚定方向，但是具体的做法还得靠自己去发现。\n\n后来又看了几篇比较偏学术的文章，例如这篇 Mixu 写的[《Single page apps in depth》](http://singlepageappbook.com/single-page.html )，对我也不太适用。他的模板都需要先编译为JS对象存放，和 AngularJS 的方法类似，但我觉得在一个小规模应用里应该有更加优雅的实现方法。\n\n找了好几天文档，我突然意识到自己浪费了不少时间。所谓理论依据应该是高层次的，解决可行性的问题，剩下的就是自己去想办法实现了。可行性不是明摆着的嘛，那么多框架不也是用原生代码实现的么？\n\n想到这儿，我就开始自己尝试了。前后一共只花了两三天时间，写出来一共一两百行JS，就基本解决了问题。其实把代码写完了回顾一下，这些方法都算不上什么创新，都是标准的东西而已。肯定有别人也这么做了，只是我不知道而已吧。\n\n可能有读者看到这儿不耐烦了：`“Talk is cheap. Show me the code.”` 好吧，下面就是代码的描述。\n\n## 老码农的实现方法\n\n### 基础对象\n首先是定义缺省的两个页面片段（缺省页面和出错页面，这两个页面是基础功能，所以放在库里）相关代码，对每个片段对应的 uri（例如 `home`）定义一个同名的对象，里面存放了对应的 html 片段文件路径、初始化方法。\n```javascript\nvar home = {};            //default partial page, which will be loaded initially\nhome.partial = \"lib/home.html\";\nhome.init = function(){   //bootstrap method\n                          //nothing but static content only to render\n}\n\nvar notfound = {};               //404 page\nnotfound.partial = \"lib/404.html\";\nnotfound.init = function(){\n    alert('URL does not exist. please check your code.');\n}\n```\n\n随后是全局变量，包含了 html 片段代码的缓存、局部刷新所在 div 的 DOM 对象和向后端服务请求返回的根数据（`rootScope`，初始化时未出现，在后面的方法中才会用到）：\n```javascript\nvar settings = {};               //global parameters\nsettings.partialCache = {};      //cache for partial pages\nsettings.divDemo = document.getElementById(\"demo\");      //div for loading partials, defined in index.html\n```\n\n### 主程序\n下面就是主程序了，所有的公用方法打包放到一个对象 `miniSPA` 中，这样可以避免污染命名空间：\n```javascript\n// Main Object here\nvar miniSPA = {};\n```\n\n然后是 changeUrl 方法，对应在 `index.html` 中有如下触发定义：\n```html\n<body onhashchange=\"miniSPA.changeUrl();\">\n```\n\n`onhashchange` 是在location.hash发生改变的时候触发的事件，能够通过它获取局部 url 的改变。在 `index.html` 中定义了如下的链接：\n```html\n    <h1> Demo Contents:</h1>\n    <a href=\"#home\">Home (Default)</a>\n    <a href=\"#postMD\">POST request</a>\n    <a href=\"#getEmoji\">GET request</a>\n    <a href=\"#wrong\">Invalid url</a>\n    <div id=\"demo\"></div>\n```\n\n每个 uri 都以 `#` 号开头，这样就能被 `onhashchange` 事件抓取到。最后的 div 就是局部刷新的 html 片段嵌入的位置。\n```javascript\nminiSPA.changeUrl = function() {          //handle url change\n    var url = location.hash.replace('#','');\n    if(url === ''){\n        url = 'home';           //default page\n    }\n    if(! window[url]){\n        url = \"notfound\";\n    }\n    miniSPA.ajaxRequest(window[url].partial, 'GET', '',function(status, page){\n        if(status == 404){\n            url = 'notfound';       //404 page\n            miniSPA.ajaxRequest(window[url].partial,'GET','',function(status, page404){\n                settings.divDemo.innerHTML = page404;\n                miniSPA.initFunc(url);              //load 404 controller\n            });\n        }\n        else{\n            settings.divDemo.innerHTML = page;\n            miniSPA.initFunc(url);              //load url controller\n        }\n    });\n}\n```\n上面的代码先获取改变后的 url，先通过 `window[url]` 找到对应的对象（类似于最上部定义的 `home` 和 `notfound`），如对象不存在（无定义的路径）则转到 `404` 处理，否则通过 `ajaxRequest` 方法获取 `window[url].partial` 中定义的 html 片段并加载到局部刷新的div，并执行 `window[url].init` 初始化方法。\n\n`ajaxRequest` 方法主要是和后端的服务进行交互，通过 `XMLHttpRequest` 发送请求（ `GET` 或 `POST`），如果获取的是 html 片段就把它缓存到 `settings.partialCache[url]` 里，因为 html 片段是相对固定的，每次请求返回的内容不会变化。如果是其他请求（比如向 Github 的 markdown 服务 POST 一个字符串）就不能缓存了。\n```javascript\nminiSPA.ajaxRequest = function(url, method, data, callback) {    //load partial page\n    if(settings.partialCache[url]){\n        callback(200, settings.partialCache[url]);\n    }\n    else {\n        var xmlhttp;\n        if(window.XMLHttpRequest){\n            xmlhttp = new XMLHttpRequest();\n            xmlhttp.open(method, url, true);\n            if(method === 'POST'){\n                xmlhttp.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");\n            }\n            xmlhttp.send(data);\n            xmlhttp.onreadystatechange = function(){\n                if(xmlhttp.readyState == 4){\n                    switch(xmlhttp.status) {\n                        case 404:                             //if the url is invalid, show the 404 page\n                            url = 'notfound';\n                            break;\n                        default:\n                            var parts = url.split('.');\n                            if(parts.length>1 && parts[parts.length-1] == 'html'){         //only cache static html pages\n                                settings.partialCache[url] = xmlhttp.responseText;        //cache partials to improve performance\n                            }\n                    }\n                    callback(xmlhttp.status, xmlhttp.responseText);\n                }\n            }\n        }\n        else{\n            alert('Sorry, your browser is too old to run this app.')\n            callback(404, {});\n        }\n    }\n}\n```\n对于不支持 `XMLHttpRequest` 的浏览器（主要是 IE 老版本），本来是可以在 else 里加上 **xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');** 的，不过，我手头也没有那么多老版本 IE 用于测试，而且老版本 IE 本来就是我深恶痛绝的东西，凭什么要支持它啊？所以就干脆直接给个 `alert` 完事。\n\n\n`render` 方法一般在每个片段的初始化方法中调用，它会设定全局变量中的根对象，并通过 `refresh` 方法渲染 html 片段。\n```javascript\nminiSPA.render = function(url){\n    settings.rootScope = window[url];\n    miniSPA.refresh(settings.divDemo, settings.rootScope);\n}\n```\n\n获取后端数据后，如何渲染 html 片段是个比较复杂的问题。这就是 DOM 操作了。总体思想就是从 html 片段的根部入手，遍历 DOM 树，逐个替换属性和文本中的占位变量（例如`<img src=\"emojis.value\">` 和 `<p>{{emojis.key}}</p>`），匹配和替换是在 `feedData()` 方法中完成的。\n\n对于 img 元素，src 属性一开始是未知的，也不能直接把变量定义到它里面，不然浏览器会报404错误，虽然不影响用户使用，但对于代码来说总归是不好看的。所以需要在获取了 `data-src` 属性值后再复制到 src 中去，这样一开始 `src` 属性是空的，就不会报错了。\n\n这里最麻烦的是 `data-repeat` 属性，这是为了批量渲染格式相同的一组元素用的。比如从 Github 获取了全套的 emoji 表情，共计 888 个（也许下次升级到1000个），就需要渲染 888 个元素，把 888 个图片及其说明放到 html 片段中去。而 html 片段中对此只有一条定义：\n\n```html\n    <ul>\n        <li data-repeat=\"emojis\" data-item=\"data\">\n            <figure>\n                <img data-src='{{data.value}}' width='100' height='100'>\n                <figcaption>{{data.key}}</figcaption>\n            </figure>\n        </li>\n    </ul>\n```\n等 888 个 emoji 表情来了之后，就要自动把 `<li>` 元素扩展到 888 个。这就需要先 `clone` 定义好的元素，然后根据后台返回的数据逐个替换元素中的占位变量。\n```javascript\nminiSPA.refresh = function(node, scope) {\n    var children = node.childNodes;\n    if(node.nodeType != 3){                            //traverse child nodes, Node.TEXT_NODE == 3\n        for(var k=0; k<node.attributes.length; k++){\n            node.setAttribute(node.attributes[k].name, miniSPA.feedData(node.attributes[k].value, scope));       //replace variables defined in attributes\n        }\n        if(node.hasAttribute('data-src')){\n            node.setAttribute('src',node.getAttribute('data-src'));             //replace src attribute\n        }\n        var childrenCount = children.length;\n        for(var j=0; j<childrenCount; j++){\n            if(children[j].nodeType != 3 && children[j].hasAttribute('data-repeat')){     //handle repeat items\n                var item = children[j].dataset.item;\n                var repeat = children[j].dataset.repeat;\n                children[j].removeAttribute('data-repeat');\n                var repeatNode = children[j];\n                for(var prop in scope[repeat]){\n                    repeatNode = children[j].cloneNode(true);                  //clone sibling nodes for the repeated node\n                    node.appendChild(repeatNode);\n                    var repeatScope = scope;\n                    var obj = {};\n                    obj.key = prop;\n                    obj.value = scope[repeat][prop];                           //add the key/value pair to current scope\n                    repeatScope[item] = obj;\n                    miniSPA.refresh(repeatNode,repeatScope);                           //iterate over all the cloned nodes\n                }\n                node.removeChild(children[j]);                                 //remove the empty template node\n            }\n            else{\n                miniSPA.refresh(children[j],scope);                                    //not for repeating, just iterate the child node\n            }\n        }\n    }\n    else{\n        node.textContent = miniSPA.feedData(node.textContent, scope);           //replace variables defined in the template\n    }\n}\n```\n从上面的代码可以看到，`refresh` 方法是一个递归执行的函数，每次处理当前 node 之后，还会递归处理所有的孩子节点。通过这种方式，就能把模板中定义的所有元素的占位变量都替换为真实数据。\n\n\n`feedData` 用来替换文本节点中的占位变量。它通过正则表达式获取`{{...}}`中的内容，并把多级属性（例如 `data.map.value`）切分开，逐级循环处理，直到最底层获得相应的数据。\n```javascript\nminiSPA.feedData = function(template, scope){                                     //replace variables with data in current scope\n    return template.replace(/\\{\\{([^}]+)\\}\\}/gmi, function(model){\n        var properties = model.substring(2,model.length-2).split('.');          //split all levels of properties\n        var result = scope;\n        for(var n in properties){\n            if(result){\n                switch(properties[n]){                  //move down to the deserved value\n                    case 'key':\n                        result = result.key;\n                        break;\n                    case 'value':\n                        result = result.value;\n                        break;\n                    case 'length':                     //get length from the object\n                        var length = 0;\n                        for(var x in result) length ++;\n                        result = length;\n                        break;\n                    default:\n                        result = result[properties[n]];\n                }\n            }\n        }\n        return result;\n    });\n}\n```\n\n`initFunc` 方法的作用是解析片段对应的初始化方法，判断其类型是否为函数，并执行它。这个方法是在 `changeUrl` 方法里调用的，每次访问路径的变化都会触发相应的初始化方法。\n```javascript\nminiSPA.initFunc = function(partial) {                            //execute the controller function responsible for current template\n    var fn = window[partial].init;\n    if(typeof fn === 'function') {\n        fn();\n    }\n}\n```\n\n最后是 `miniSPA` 库自身的初始化。很简单，就是先获取 `404.html` 片段并缓存到 `settings.partialCache.notfound` 中，以便在路径变化时使用。当路径不合法时，就会从缓存中取出404片段并显示在局部刷新的 div 中。\n```javascript\nminiSPA.ajaxRequest('lib/404.html', 'GET','',function(status, partial){\n    settings.partialCache.notfound = partial;\n});        //cache 404 page first\n```\n\n好了，核心的代码就是这么多。整个 js 文件才区区 155 行，比起那些动辄几万行的框架是不是简单得不能再简单了？\n\n有了上面的 `miniSPA.js` 代码以及配套的 `404.html` 和 `home.html`，并把它们打包放在 `lib` 目录下，下面就可以来看我的应用里有啥内容。\n\n### 应用代码\n说到应用那就更简单了，`app.js` 一共30行，实现了一个 `GET` 和一个 `POST` 访问。\n\n首先是 `getEmoji` 对象，定义了一个 html 片段文件路径和一个初始化方法。初始化方法中分别调用了 `miniSPA` 中的 `ajaxRequest` 方法（用于获取 Github API 提供的 emoji 表情数据， JSON格式）和 `render` 方法（用来渲染对应的 html 片段）。\n```javascript\nvar getEmoji = {};\ngetEmoji.partial = \"getEmoji.html\"\ngetEmoji.init = function(){\n    document.getElementById('spinner').style.visibility = 'visible';\n    document.getElementById('content').style.visibility = 'hidden';\n    miniSPA.ajaxRequest('https://api.github.com/emojis','GET','',function(status, partial){\n        getEmoji.emojis = JSON.parse(partial);\n        miniSPA.render('getEmoji');         //render related partial page with data returned from the server\n        document.getElementById('content').style.visibility = 'visible';\n        document.getElementById('spinner').style.visibility = 'hidden';\n    });\n}\n```\n\n然后是 `postMD` 对象，它除了 html 片段文件路径和初始化方法（因为初始化不需要获取外部数据，所以只需要调用 `render` 方法就可以了）之外，重点在于 `submit` 方法。`submit` 会把用户提交的输入文本和其他两个选项打包 POST 给 Github 的 markdown API，并获取后台解析标记返回的 html。\n```javascript\nvar postMD = {};\npostMD.partial = \"postMD.html\";\npostMD.init = function(){\n    miniSPA.render('postMD');               //render related partial page\n}\npostMD.submit = function(){\n    document.getElementById('spinner').style.visibility = 'visible';\n    var mdText = document.getElementById('mdText');\n    var md = document.getElementById('md');\n    var data = '{\"text\":\"'+mdText.value.replace(/\\n/g, '<br>')+'\",\"mode\": \"gfm\",\"context\": \"github/gollum\"}';\n    miniSPA.ajaxRequest('https://api.github.com/markdown', 'POST', data,function(status, page){\n        document.getElementById('spinner').style.visibility = 'hidden';\n        md.innerHTML = page;                //render markdown partial returned from the server\n    });\n    mdText.value = '';\n}\nminiSPA.changeUrl();                        //initialize\n```\n\n这两个对象对应的 html 片段如下：\n\ngetEmoji.html :\n```html\n<h2>GET request: Fetch emojis from Github pulic API.</h2>\n<p> This is a list of emojis get from https://api.github.com/emojis: </p>\n<i id=\"spinner\" class=\"csspinner duo\"></i>\n<span id=\"content\">\n    <h4>Get <strong class=\"highlight\">{{emojis.length}}</strong> items totally.</h4>\n    <hr>\n    <ul>\n        <li data-repeat=\"emojis\" data-item=\"data\">\n            <figure>\n                <img data-src='{{data.value}}' width='100' height='100'>\n                <figcaption>{{data.key}}</figcaption>\n            </figure>\n        </li>\n    </ul>\n</span>\n```\n\npostMD.html :\n```html\n<h2> POST request: send MD text and get rendered HTML</h2>\n<p> markdown text here (for example:  <strong>Hello world github/linguist#1 **cool**, and #1! </strong>): </p>\n<textarea id=\"mdText\" cols=\"80\" rows=\"6\"></textarea>\n<button onclick=\"postMD.submit();\">submit</button>\n<hr>\n<h4>Rendered elements from Github API (https://api.github.com/markdown):</h4>\n<i id=\"spinner\" class=\"csspinner duo\"></i>\n<div id=\"md\"></div>\n```\n\n\n## 完整源代码\n源代码在 [gh-pages](https://github.com/coderLMN/framework-free-single-page-app/tree/gh-pages) 分支里可以看到。\n\n## 演示地址\n以上代码的在线演示可以在 [我的 Github 项目页面](https://coderlmn.github.io/framework-free-single-page-app/ ) 看到。\n\n以上演示代码已经在 `Chrome`, `Firefox`, `Safari` 和 `Opera` 较新版本上测试过。`IE 9` 以上版本估计也可以，不过没测过。\n\n另外，这些代码还有不少值得优化的地方，不过时间有限，主要是为了达到演示目的，让代码保持精简为好，所以暂时就不去改它了。\n\n## 前端技术探讨\n\n我的[另外一个 repo](https://github.com/coderLMN/frontEndCourse) 里有我自己关于前端技术的一些思考和尝试。它对应的 [gh-pages](https://coderlmn.github.io/frontEndCourse/) 分支里有一些演示，还有几篇翻译文章，也欢迎讨论和指正。\n\n\n## 补充讨论\n有同学提出了事件处理的问题，我更新了一下演示，说明如下：\n\n事件的处理可以直接添加到元素上，不用改动现有代码。对于 data-repeat 元素，可以在事件响应方法的参数里传递它的 id 等唯一标识，例如在\n\n```html\n<img data-src='{{data.value}}’ width=’80’ height=’80’>\n```\n\n元素里加上\n\n```html\nonclick=”getEmoji.clicked(‘{{data.key}}’);”\n```\n\nminiSPA.refresh() 方法会自动把{{data.key}} 解析为实际的参数。\n\n然后在 app.js 里对应的 partial 对象里定义响应方法，例如：\n\n```javascript\ngetEmoji.clicked = function(id){\n    alert('clicked: '+ id);\n}\n```\n\n现在，在 emoji 示例中点击每个图标，就会出现上述代码产生的 alert 提示框。\n"
  }
]