sunspot_solr 2.2.2 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. checksums.yaml +4 -4
  2. data/bin/sunspot-solr +2 -6
  3. data/lib/sunspot/solr/server.rb +2 -3
  4. data/solr/README.txt +181 -181
  5. data/solr/bin/post +29 -19
  6. data/solr/bin/solr +247 -428
  7. data/solr/bin/solr.cmd +102 -256
  8. data/solr/bin/solr.in.cmd +15 -7
  9. data/solr/bin/solr.in.sh +26 -12
  10. data/solr/server/README.txt +110 -113
  11. data/solr/server/contexts/solr-jetty-context.xml +8 -8
  12. data/solr/server/etc/jetty-http.xml +47 -0
  13. data/solr/server/etc/jetty-https-ssl.xml +175 -159
  14. data/solr/server/etc/jetty-https.xml +53 -0
  15. data/solr/server/etc/jetty-ssl.xml +46 -0
  16. data/solr/server/etc/jetty.xml +189 -167
  17. data/solr/server/etc/webdefault.xml +527 -527
  18. data/solr/server/lib/javax.servlet-api-3.1.0.jar +0 -0
  19. data/solr/server/lib/jetty-continuation-9.2.11.v20150529.jar +0 -0
  20. data/solr/server/lib/jetty-deploy-9.2.11.v20150529.jar +0 -0
  21. data/solr/server/lib/jetty-http-9.2.11.v20150529.jar +0 -0
  22. data/solr/server/lib/jetty-io-9.2.11.v20150529.jar +0 -0
  23. data/solr/server/lib/jetty-jmx-9.2.11.v20150529.jar +0 -0
  24. data/solr/server/lib/jetty-rewrite-9.2.11.v20150529.jar +0 -0
  25. data/solr/server/lib/jetty-security-9.2.11.v20150529.jar +0 -0
  26. data/solr/server/lib/jetty-server-9.2.11.v20150529.jar +0 -0
  27. data/solr/server/lib/jetty-servlet-9.2.11.v20150529.jar +0 -0
  28. data/solr/server/lib/jetty-servlets-9.2.11.v20150529.jar +0 -0
  29. data/solr/server/lib/jetty-util-9.2.11.v20150529.jar +0 -0
  30. data/solr/server/lib/jetty-webapp-9.2.11.v20150529.jar +0 -0
  31. data/solr/server/lib/jetty-xml-9.2.11.v20150529.jar +0 -0
  32. data/solr/server/modules/http.mod +9 -0
  33. data/solr/server/modules/https.mod +9 -0
  34. data/solr/server/modules/server.mod +11 -0
  35. data/solr/server/modules/ssl.mod +9 -0
  36. data/solr/server/resources/jetty-logging.properties +1 -0
  37. data/solr/server/resources/log4j.properties +24 -24
  38. data/solr/server/solr-webapp/webapp/WEB-INF/lib/commons-exec-1.3.jar +0 -0
  39. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{hadoop-annotations-2.3.0.jar → hadoop-annotations-2.6.0.jar} +0 -0
  40. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-auth-2.6.0.jar +0 -0
  41. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-common-2.6.0.jar +0 -0
  42. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-hdfs-2.6.0.jar +0 -0
  43. data/solr/server/solr-webapp/webapp/WEB-INF/lib/htrace-core-3.0.4.jar +0 -0
  44. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpclient-4.4.1.jar +0 -0
  45. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpcore-4.4.1.jar +0 -0
  46. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpmime-4.4.1.jar +0 -0
  47. data/solr/server/solr-webapp/webapp/WEB-INF/lib/jackson-core-2.5.4.jar +0 -0
  48. data/solr/server/solr-webapp/webapp/WEB-INF/lib/jackson-dataformat-smile-2.5.4.jar +0 -0
  49. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-analyzers-common-5.0.0.jar → lucene-analyzers-common-5.3.1.jar} +0 -0
  50. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-analyzers-kuromoji-5.0.0.jar → lucene-analyzers-kuromoji-5.3.1.jar} +0 -0
  51. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-analyzers-phonetic-5.0.0.jar → lucene-analyzers-phonetic-5.3.1.jar} +0 -0
  52. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-backward-codecs-5.3.1.jar +0 -0
  53. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-codecs-5.3.1.jar +0 -0
  54. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-core-5.3.1.jar +0 -0
  55. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-expressions-5.0.0.jar → lucene-expressions-5.3.1.jar} +0 -0
  56. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-grouping-5.0.0.jar → lucene-grouping-5.3.1.jar} +0 -0
  57. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-highlighter-5.3.1.jar +0 -0
  58. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-join-5.3.1.jar +0 -0
  59. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-memory-5.3.1.jar +0 -0
  60. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-misc-5.3.1.jar +0 -0
  61. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-queries-5.3.1.jar +0 -0
  62. data/solr/server/solr-webapp/webapp/WEB-INF/lib/{lucene-queryparser-5.0.0.jar → lucene-queryparser-5.3.1.jar} +0 -0
  63. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-sandbox-5.3.1.jar +0 -0
  64. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-spatial-5.3.1.jar +0 -0
  65. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-suggest-5.3.1.jar +0 -0
  66. data/solr/server/solr-webapp/webapp/WEB-INF/lib/org.restlet-2.3.0.jar +0 -0
  67. data/solr/server/solr-webapp/webapp/WEB-INF/lib/org.restlet.ext.servlet-2.3.0.jar +0 -0
  68. data/solr/server/solr-webapp/webapp/WEB-INF/lib/solr-core-5.3.1.jar +0 -0
  69. data/solr/server/solr-webapp/webapp/WEB-INF/lib/solr-solrj-5.3.1.jar +0 -0
  70. data/solr/server/solr-webapp/webapp/WEB-INF/lib/t-digest-3.1.jar +0 -0
  71. data/solr/server/solr-webapp/webapp/WEB-INF/web.xml +169 -181
  72. data/solr/server/solr-webapp/webapp/WEB-INF/weblogic.xml +28 -28
  73. data/solr/server/solr-webapp/webapp/admin.html +164 -163
  74. data/solr/server/solr-webapp/webapp/css/angular/analysis.css +304 -0
  75. data/solr/server/solr-webapp/webapp/css/angular/chosen.css +465 -0
  76. data/solr/server/solr-webapp/webapp/css/angular/cloud.css +398 -0
  77. data/solr/server/solr-webapp/webapp/css/angular/common.css +724 -0
  78. data/solr/server/solr-webapp/webapp/css/angular/cores.css +233 -0
  79. data/solr/server/solr-webapp/webapp/css/angular/dataimport.css +370 -0
  80. data/solr/server/solr-webapp/webapp/css/angular/documents.css +179 -0
  81. data/solr/server/solr-webapp/webapp/css/angular/files.css +53 -0
  82. data/solr/server/solr-webapp/webapp/css/angular/index.css +206 -0
  83. data/solr/server/solr-webapp/webapp/css/angular/logging.css +376 -0
  84. data/solr/server/solr-webapp/webapp/css/angular/menu.css +321 -0
  85. data/solr/server/solr-webapp/webapp/css/angular/plugins.css +212 -0
  86. data/solr/server/solr-webapp/webapp/css/angular/query.css +162 -0
  87. data/solr/server/solr-webapp/webapp/css/angular/replication.css +500 -0
  88. data/solr/server/solr-webapp/webapp/css/angular/schema-browser.css +567 -0
  89. data/solr/server/solr-webapp/webapp/css/angular/segments.css +173 -0
  90. data/solr/server/solr-webapp/webapp/css/angular/threads.css +161 -0
  91. data/solr/server/solr-webapp/webapp/css/chosen.css +421 -421
  92. data/solr/server/solr-webapp/webapp/css/styles/analysis.css +311 -311
  93. data/solr/server/solr-webapp/webapp/css/styles/cloud.css +410 -410
  94. data/solr/server/solr-webapp/webapp/css/styles/common.css +701 -701
  95. data/solr/server/solr-webapp/webapp/css/styles/cores.css +244 -244
  96. data/solr/server/solr-webapp/webapp/css/styles/dashboard.css +155 -155
  97. data/solr/server/solr-webapp/webapp/css/styles/dataimport.css +403 -403
  98. data/solr/server/solr-webapp/webapp/css/styles/documents.css +197 -197
  99. data/solr/server/solr-webapp/webapp/css/styles/files.css +54 -54
  100. data/solr/server/solr-webapp/webapp/css/styles/index.css +207 -207
  101. data/solr/server/solr-webapp/webapp/css/styles/java-properties.css +52 -52
  102. data/solr/server/solr-webapp/webapp/css/styles/logging.css +391 -391
  103. data/solr/server/solr-webapp/webapp/css/styles/menu.css +329 -328
  104. data/solr/server/solr-webapp/webapp/css/styles/plugins.css +195 -195
  105. data/solr/server/solr-webapp/webapp/css/styles/query.css +173 -173
  106. data/solr/server/solr-webapp/webapp/css/styles/replication.css +515 -515
  107. data/solr/server/solr-webapp/webapp/css/styles/schema-browser.css +578 -578
  108. data/solr/server/solr-webapp/webapp/css/styles/segments.css +145 -0
  109. data/solr/server/solr-webapp/webapp/css/styles/threads.css +172 -172
  110. data/solr/server/solr-webapp/webapp/img/chosen-sprite-2x.png +0 -0
  111. data/solr/server/solr-webapp/webapp/img/filetypes/README +27 -27
  112. data/solr/server/solr-webapp/webapp/img/solr.svg +39 -39
  113. data/solr/server/solr-webapp/webapp/index.html +208 -0
  114. data/solr/server/solr-webapp/webapp/js/angular/app.js +713 -0
  115. data/solr/server/solr-webapp/webapp/js/angular/controllers/analysis.js +199 -0
  116. data/solr/server/solr-webapp/webapp/js/angular/controllers/cloud.js +528 -0
  117. data/solr/server/solr-webapp/webapp/js/angular/controllers/core-overview.js +225 -0
  118. data/solr/server/solr-webapp/webapp/js/angular/controllers/cores.js +465 -0
  119. data/solr/server/solr-webapp/webapp/js/angular/controllers/dataimport.js +284 -0
  120. data/solr/server/solr-webapp/webapp/js/angular/controllers/documents.js +139 -0
  121. data/solr/server/solr-webapp/webapp/js/angular/controllers/files.js +92 -0
  122. data/solr/server/solr-webapp/webapp/js/angular/controllers/index.js +95 -0
  123. data/solr/server/solr-webapp/webapp/js/angular/controllers/java-properties.js +45 -0
  124. data/solr/server/solr-webapp/webapp/js/angular/controllers/logging.js +146 -0
  125. data/solr/server/solr-webapp/webapp/js/angular/controllers/plugins.js +166 -0
  126. data/solr/server/solr-webapp/webapp/js/angular/controllers/query.js +99 -0
  127. data/solr/server/solr-webapp/webapp/js/angular/controllers/replication.js +227 -0
  128. data/solr/server/solr-webapp/webapp/js/angular/controllers/schema-browser.js +432 -0
  129. data/solr/server/solr-webapp/webapp/js/angular/controllers/segments.js +94 -0
  130. data/solr/server/solr-webapp/webapp/js/angular/controllers/threads.js +51 -0
  131. data/solr/server/solr-webapp/webapp/js/angular/services.js +214 -0
  132. data/solr/server/solr-webapp/webapp/js/lib/ZeroClipboard.js +342 -342
  133. data/solr/server/solr-webapp/webapp/js/lib/chosen.js +982 -982
  134. data/solr/server/solr-webapp/webapp/js/lib/console.js +29 -29
  135. data/solr/server/solr-webapp/webapp/js/lib/d3.js +9373 -9373
  136. data/solr/server/solr-webapp/webapp/js/lib/highlight.js +31 -31
  137. data/solr/server/solr-webapp/webapp/js/lib/jquery-1.7.2.min.js +30 -30
  138. data/solr/server/solr-webapp/webapp/js/lib/jquery.ajaxfileupload.js +184 -184
  139. data/solr/server/solr-webapp/webapp/js/lib/jquery.blockUI.js +523 -523
  140. data/solr/server/solr-webapp/webapp/js/lib/jquery.cookie.js +71 -71
  141. data/solr/server/solr-webapp/webapp/js/lib/jquery.form.js +806 -806
  142. data/solr/server/solr-webapp/webapp/js/lib/jquery.jstree.js +3534 -3534
  143. data/solr/server/solr-webapp/webapp/js/lib/jquery.sammy.js +1863 -1863
  144. data/solr/server/solr-webapp/webapp/js/lib/jquery.timeago.js +189 -189
  145. data/solr/server/solr-webapp/webapp/js/lib/linker.js +48 -48
  146. data/solr/server/solr-webapp/webapp/js/lib/naturalSort.js +82 -0
  147. data/solr/server/solr-webapp/webapp/js/lib/order.js +216 -216
  148. data/solr/server/solr-webapp/webapp/js/main.js +60 -58
  149. data/solr/server/solr-webapp/webapp/js/require.js +11349 -11349
  150. data/solr/server/solr-webapp/webapp/js/scripts/analysis.js +545 -545
  151. data/solr/server/solr-webapp/webapp/js/scripts/app.js +680 -679
  152. data/solr/server/solr-webapp/webapp/js/scripts/cloud.js +877 -877
  153. data/solr/server/solr-webapp/webapp/js/scripts/cores.js +719 -719
  154. data/solr/server/solr-webapp/webapp/js/scripts/dashboard.js +562 -562
  155. data/solr/server/solr-webapp/webapp/js/scripts/dataimport.js +812 -812
  156. data/solr/server/solr-webapp/webapp/js/scripts/documents.js +370 -370
  157. data/solr/server/solr-webapp/webapp/js/scripts/files.js +265 -265
  158. data/solr/server/solr-webapp/webapp/js/scripts/index.js +340 -340
  159. data/solr/server/solr-webapp/webapp/js/scripts/java-properties.js +106 -106
  160. data/solr/server/solr-webapp/webapp/js/scripts/logging.js +578 -576
  161. data/solr/server/solr-webapp/webapp/js/scripts/ping.js +72 -72
  162. data/solr/server/solr-webapp/webapp/js/scripts/plugins.js +462 -462
  163. data/solr/server/solr-webapp/webapp/js/scripts/query.js +229 -229
  164. data/solr/server/solr-webapp/webapp/js/scripts/replication.js +527 -527
  165. data/solr/server/solr-webapp/webapp/js/scripts/schema-browser.js +1229 -1229
  166. data/solr/server/solr-webapp/webapp/js/scripts/segments.js +206 -0
  167. data/solr/server/solr-webapp/webapp/js/scripts/threads.js +158 -158
  168. data/solr/server/solr-webapp/webapp/libs/angular-chosen.js +139 -0
  169. data/solr/server/solr-webapp/webapp/libs/angular-cookies.js +229 -0
  170. data/solr/server/solr-webapp/webapp/libs/angular-cookies.min.js +31 -0
  171. data/solr/server/solr-webapp/webapp/libs/angular-resource.min.js +36 -0
  172. data/solr/server/solr-webapp/webapp/libs/angular-route.js +1018 -0
  173. data/solr/server/solr-webapp/webapp/libs/angular-route.min.js +38 -0
  174. data/solr/server/solr-webapp/webapp/libs/angular-sanitize.js +703 -0
  175. data/solr/server/solr-webapp/webapp/libs/angular-sanitize.min.js +39 -0
  176. data/solr/server/solr-webapp/webapp/libs/angular.js +26093 -0
  177. data/solr/server/solr-webapp/webapp/libs/angular.min.js +273 -0
  178. data/solr/server/solr-webapp/webapp/libs/chosen.jquery.js +1194 -0
  179. data/solr/server/solr-webapp/webapp/libs/chosen.jquery.min.js +30 -0
  180. data/solr/server/solr-webapp/webapp/libs/d3.js +9373 -0
  181. data/solr/server/solr-webapp/webapp/libs/highlight.js +31 -0
  182. data/solr/server/solr-webapp/webapp/libs/jquery-2.1.3.min.js +29 -0
  183. data/solr/server/solr-webapp/webapp/libs/jquery.jstree.js +3534 -0
  184. data/solr/server/solr-webapp/webapp/libs/ngtimeago.js +102 -0
  185. data/solr/server/solr-webapp/webapp/partials/analysis.html +128 -0
  186. data/solr/server/solr-webapp/webapp/partials/cloud.html +104 -0
  187. data/solr/server/solr-webapp/webapp/partials/core_overview.html +227 -0
  188. data/solr/server/solr-webapp/webapp/partials/cores.html +231 -0
  189. data/solr/server/solr-webapp/webapp/partials/dataimport.html +209 -0
  190. data/solr/server/solr-webapp/webapp/partials/documents.html +118 -0
  191. data/solr/server/solr-webapp/webapp/partials/files.html +47 -0
  192. data/solr/server/solr-webapp/webapp/partials/index.html +261 -0
  193. data/solr/server/solr-webapp/webapp/partials/java-properties.html +27 -0
  194. data/solr/server/solr-webapp/webapp/partials/logging-levels.html +56 -0
  195. data/solr/server/solr-webapp/webapp/partials/logging.html +56 -0
  196. data/solr/server/solr-webapp/webapp/partials/plugins.html +72 -0
  197. data/solr/server/solr-webapp/webapp/partials/query.html +356 -0
  198. data/solr/server/solr-webapp/webapp/partials/replication.html +239 -0
  199. data/solr/server/solr-webapp/webapp/partials/schema-browser.html +206 -0
  200. data/solr/server/solr-webapp/webapp/partials/segments.html +99 -0
  201. data/solr/server/solr-webapp/webapp/partials/threads.html +65 -0
  202. data/solr/server/solr-webapp/webapp/tpl/analysis.html +83 -83
  203. data/solr/server/solr-webapp/webapp/tpl/cloud.html +87 -87
  204. data/solr/server/solr-webapp/webapp/tpl/cores.html +226 -226
  205. data/solr/server/solr-webapp/webapp/tpl/dashboard.html +201 -201
  206. data/solr/server/solr-webapp/webapp/tpl/dataimport.html +183 -183
  207. data/solr/server/solr-webapp/webapp/tpl/documents.html +107 -107
  208. data/solr/server/solr-webapp/webapp/tpl/files.html +44 -44
  209. data/solr/server/solr-webapp/webapp/tpl/index.html +250 -250
  210. data/solr/server/solr-webapp/webapp/tpl/logging.html +23 -23
  211. data/solr/server/solr-webapp/webapp/tpl/plugins.html +39 -39
  212. data/solr/server/solr-webapp/webapp/tpl/query.html +361 -361
  213. data/solr/server/solr-webapp/webapp/tpl/replication.html +216 -216
  214. data/solr/server/solr-webapp/webapp/tpl/schema-browser.html +192 -192
  215. data/solr/server/solr-webapp/webapp/tpl/segments.html +49 -0
  216. data/solr/server/solr-webapp/webapp/tpl/threads.html +56 -56
  217. data/solr/server/solr/README.txt +77 -77
  218. data/solr/server/solr/solr.xml +51 -51
  219. data/solr/server/solr/zoo.cfg +17 -17
  220. data/solr/server/start.jar +0 -0
  221. data/spec/server_spec.rb +3 -8
  222. metadata +132 -43
  223. data/solr/server/lib/jetty-continuation-8.1.10.v20130312.jar +0 -0
  224. data/solr/server/lib/jetty-deploy-8.1.10.v20130312.jar +0 -0
  225. data/solr/server/lib/jetty-http-8.1.10.v20130312.jar +0 -0
  226. data/solr/server/lib/jetty-io-8.1.10.v20130312.jar +0 -0
  227. data/solr/server/lib/jetty-jmx-8.1.10.v20130312.jar +0 -0
  228. data/solr/server/lib/jetty-security-8.1.10.v20130312.jar +0 -0
  229. data/solr/server/lib/jetty-server-8.1.10.v20130312.jar +0 -0
  230. data/solr/server/lib/jetty-servlet-8.1.10.v20130312.jar +0 -0
  231. data/solr/server/lib/jetty-util-8.1.10.v20130312.jar +0 -0
  232. data/solr/server/lib/jetty-webapp-8.1.10.v20130312.jar +0 -0
  233. data/solr/server/lib/jetty-xml-8.1.10.v20130312.jar +0 -0
  234. data/solr/server/lib/servlet-api-3.0.jar +0 -0
  235. data/solr/server/solr-webapp/webapp/.gitignore +0 -1
  236. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-auth-2.3.0.jar +0 -0
  237. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-common-2.3.0.jar +0 -0
  238. data/solr/server/solr-webapp/webapp/WEB-INF/lib/hadoop-hdfs-2.3.0.jar +0 -0
  239. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpclient-4.3.1.jar +0 -0
  240. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpcore-4.3.jar +0 -0
  241. data/solr/server/solr-webapp/webapp/WEB-INF/lib/httpmime-4.3.1.jar +0 -0
  242. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-backward-codecs-5.0.0.jar +0 -0
  243. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-codecs-5.0.0.jar +0 -0
  244. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-core-5.0.0.jar +0 -0
  245. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-highlighter-5.0.0.jar +0 -0
  246. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-join-5.0.0.jar +0 -0
  247. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-memory-5.0.0.jar +0 -0
  248. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-misc-5.0.0.jar +0 -0
  249. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-queries-5.0.0.jar +0 -0
  250. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-spatial-5.0.0.jar +0 -0
  251. data/solr/server/solr-webapp/webapp/WEB-INF/lib/lucene-suggest-5.0.0.jar +0 -0
  252. data/solr/server/solr-webapp/webapp/WEB-INF/lib/org.restlet-2.1.1.jar +0 -0
  253. data/solr/server/solr-webapp/webapp/WEB-INF/lib/org.restlet.ext.servlet-2.1.1.jar +0 -0
  254. data/solr/server/solr-webapp/webapp/WEB-INF/lib/solr-core-5.0.0.jar +0 -0
  255. data/solr/server/solr-webapp/webapp/WEB-INF/lib/solr-solrj-5.0.0.jar +0 -0
  256. data/solr/server/webapps/solr.war +0 -0
@@ -1,1863 +1,1863 @@
1
- // name: sammy
2
- // version: 0.6.2
3
- /*
4
-
5
- Copyright (c) 2008 Aaron Quint, Quirkey NYC, LLC
6
-
7
- Permission is hereby granted, free of charge, to any person obtaining a copy
8
- of this software and associated documentation files (the "Software"), to deal
9
- in the Software without restriction, including without limitation the rights
10
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- copies of the Software, and to permit persons to whom the Software is
12
- furnished to do so, subject to the following conditions:
13
-
14
- The above copyright notice and this permission notice shall be included in
15
- all copies or substantial portions of the Software.
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
- THE SOFTWARE.
24
-
25
- */
26
-
27
- (function($, window) {
28
-
29
- var Sammy,
30
- PATH_REPLACER = "([^\/]+)",
31
- PATH_NAME_MATCHER = /:([\w\d]+)/g,
32
- QUERY_STRING_MATCHER = /\?([^#]*)$/,
33
- // mainly for making `arguments` an Array
34
- _makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); },
35
- // borrowed from jQuery
36
- _isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; },
37
- _isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; },
38
- _decode = decodeURIComponent,
39
- _encode = encodeURIComponent,
40
- _escapeHTML = function(s) {
41
- return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
42
- },
43
- _routeWrapper = function(verb) {
44
- return function(path, callback) { return this.route.apply(this, [verb, path, callback]); };
45
- },
46
- _template_cache = {},
47
- loggers = [];
48
-
49
-
50
- // `Sammy` (also aliased as $.sammy) is not only the namespace for a
51
- // number of prototypes, it's also a top level method that allows for easy
52
- // creation/management of `Sammy.Application` instances. There are a
53
- // number of different forms for `Sammy()` but each returns an instance
54
- // of `Sammy.Application`. When a new instance is created using
55
- // `Sammy` it is added to an Object called `Sammy.apps`. This
56
- // provides for an easy way to get at existing Sammy applications. Only one
57
- // instance is allowed per `element_selector` so when calling
58
- // `Sammy('selector')` multiple times, the first time will create
59
- // the application and the following times will extend the application
60
- // already added to that selector.
61
- //
62
- // ### Example
63
- //
64
- // // returns the app at #main or a new app
65
- // Sammy('#main')
66
- //
67
- // // equivilent to "new Sammy.Application", except appends to apps
68
- // Sammy();
69
- // Sammy(function() { ... });
70
- //
71
- // // extends the app at '#main' with function.
72
- // Sammy('#main', function() { ... });
73
- //
74
- Sammy = function() {
75
- var args = _makeArray(arguments),
76
- app, selector;
77
- Sammy.apps = Sammy.apps || {};
78
- if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
79
- return Sammy.apply(Sammy, ['body'].concat(args));
80
- } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
81
- app = Sammy.apps[selector] || new Sammy.Application();
82
- app.element_selector = selector;
83
- if (args.length > 0) {
84
- $.each(args, function(i, plugin) {
85
- app.use(plugin);
86
- });
87
- }
88
- // if the selector changes make sure the refrence in Sammy.apps changes
89
- if (app.element_selector != selector) {
90
- delete Sammy.apps[selector];
91
- }
92
- Sammy.apps[app.element_selector] = app;
93
- return app;
94
- }
95
- };
96
-
97
- Sammy.VERSION = '0.6.2';
98
-
99
- // Add to the global logger pool. Takes a function that accepts an
100
- // unknown number of arguments and should print them or send them somewhere
101
- // The first argument is always a timestamp.
102
- Sammy.addLogger = function(logger) {
103
- loggers.push(logger);
104
- };
105
-
106
- // Sends a log message to each logger listed in the global
107
- // loggers pool. Can take any number of arguments.
108
- // Also prefixes the arguments with a timestamp.
109
- Sammy.log = function() {
110
- var args = _makeArray(arguments);
111
- args.unshift("[" + Date() + "]");
112
- $.each(loggers, function(i, logger) {
113
- logger.apply(Sammy, args);
114
- });
115
- };
116
-
117
- if (typeof window.console != 'undefined') {
118
- if (_isFunction(window.console.log.apply)) {
119
- Sammy.addLogger(function() {
120
- window.console.log.apply(window.console, arguments);
121
- });
122
- } else {
123
- Sammy.addLogger(function() {
124
- window.console.log(arguments);
125
- });
126
- }
127
- } else if (typeof console != 'undefined') {
128
- Sammy.addLogger(function() {
129
- console.log.apply(console, arguments);
130
- });
131
- }
132
-
133
- $.extend(Sammy, {
134
- makeArray: _makeArray,
135
- isFunction: _isFunction,
136
- isArray: _isArray
137
- })
138
-
139
- // Sammy.Object is the base for all other Sammy classes. It provides some useful
140
- // functionality, including cloning, iterating, etc.
141
- Sammy.Object = function(obj) { // constructor
142
- return $.extend(this, obj || {});
143
- };
144
-
145
- $.extend(Sammy.Object.prototype, {
146
-
147
- // Escape HTML in string, use in templates to prevent script injection.
148
- // Also aliased as `h()`
149
- escapeHTML: _escapeHTML,
150
- h: _escapeHTML,
151
-
152
- // Returns a copy of the object with Functions removed.
153
- toHash: function() {
154
- var json = {};
155
- $.each(this, function(k,v) {
156
- if (!_isFunction(v)) {
157
- json[k] = v;
158
- }
159
- });
160
- return json;
161
- },
162
-
163
- // Renders a simple HTML version of this Objects attributes.
164
- // Does not render functions.
165
- // For example. Given this Sammy.Object:
166
- //
167
- // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
168
- // s.toHTML() //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
169
- //
170
- toHTML: function() {
171
- var display = "";
172
- $.each(this, function(k, v) {
173
- if (!_isFunction(v)) {
174
- display += "<strong>" + k + "</strong> " + v + "<br />";
175
- }
176
- });
177
- return display;
178
- },
179
-
180
- // Returns an array of keys for this object. If `attributes_only`
181
- // is true will not return keys that map to a `function()`
182
- keys: function(attributes_only) {
183
- var keys = [];
184
- for (var property in this) {
185
- if (!_isFunction(this[property]) || !attributes_only) {
186
- keys.push(property);
187
- }
188
- }
189
- return keys;
190
- },
191
-
192
- // Checks if the object has a value at `key` and that the value is not empty
193
- has: function(key) {
194
- return this[key] && $.trim(this[key].toString()) != '';
195
- },
196
-
197
- // convenience method to join as many arguments as you want
198
- // by the first argument - useful for making paths
199
- join: function() {
200
- var args = _makeArray(arguments);
201
- var delimiter = args.shift();
202
- return args.join(delimiter);
203
- },
204
-
205
- // Shortcut to Sammy.log
206
- log: function() {
207
- Sammy.log.apply(Sammy, arguments);
208
- },
209
-
210
- // Returns a string representation of this object.
211
- // if `include_functions` is true, it will also toString() the
212
- // methods of this object. By default only prints the attributes.
213
- toString: function(include_functions) {
214
- var s = [];
215
- $.each(this, function(k, v) {
216
- if (!_isFunction(v) || include_functions) {
217
- s.push('"' + k + '": ' + v.toString());
218
- }
219
- });
220
- return "Sammy.Object: {" + s.join(',') + "}";
221
- }
222
- });
223
-
224
- // The HashLocationProxy is the default location proxy for all Sammy applications.
225
- // A location proxy is a prototype that conforms to a simple interface. The purpose
226
- // of a location proxy is to notify the Sammy.Application its bound to when the location
227
- // or 'external state' changes. The HashLocationProxy considers the state to be
228
- // changed when the 'hash' (window.location.hash / '#') changes. It does this in two
229
- // different ways depending on what browser you are using. The newest browsers
230
- // (IE, Safari > 4, FF >= 3.6) support a 'onhashchange' DOM event, thats fired whenever
231
- // the location.hash changes. In this situation the HashLocationProxy just binds
232
- // to this event and delegates it to the application. In the case of older browsers
233
- // a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier,
234
- // the HashLocationProxy allows the poller to be a global object, eliminating the
235
- // need for multiple pollers even when thier are multiple apps on the page.
236
- Sammy.HashLocationProxy = function(app, run_interval_every) {
237
- this.app = app;
238
- // set is native to false and start the poller immediately
239
- this.is_native = false;
240
- this._startPolling(run_interval_every);
241
- };
242
-
243
- Sammy.HashLocationProxy.prototype = {
244
-
245
- // bind the proxy events to the current app.
246
- bind: function() {
247
- var proxy = this, app = this.app;
248
- $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
249
- // if we receive a native hash change event, set the proxy accordingly
250
- // and stop polling
251
- if (proxy.is_native === false && !non_native) {
252
- Sammy.log('native hash change exists, using');
253
- proxy.is_native = true;
254
- window.clearInterval(Sammy.HashLocationProxy._interval);
255
- }
256
- app.trigger('location-changed');
257
- });
258
- if (!Sammy.HashLocationProxy._bindings) {
259
- Sammy.HashLocationProxy._bindings = 0;
260
- }
261
- Sammy.HashLocationProxy._bindings++;
262
- },
263
-
264
- // unbind the proxy events from the current app
265
- unbind: function() {
266
- $(window).unbind('hashchange.' + this.app.eventNamespace());
267
- Sammy.HashLocationProxy._bindings--;
268
- if (Sammy.HashLocationProxy._bindings <= 0) {
269
- window.clearInterval(Sammy.HashLocationProxy._interval);
270
- }
271
- },
272
-
273
- // get the current location from the hash.
274
- getLocation: function() {
275
- // Bypass the `window.location.hash` attribute. If a question mark
276
- // appears in the hash IE6 will strip it and all of the following
277
- // characters from `window.location.hash`.
278
- var matches = window.location.toString().match(/^[^#]*(#.+)$/);
279
- return matches ? matches[1] : '';
280
- },
281
-
282
- // set the current location to `new_location`
283
- setLocation: function(new_location) {
284
- return (window.location = new_location);
285
- },
286
-
287
- _startPolling: function(every) {
288
- // set up interval
289
- var proxy = this;
290
- if (!Sammy.HashLocationProxy._interval) {
291
- if (!every) { every = 10; }
292
- var hashCheck = function() {
293
- var current_location = proxy.getLocation();
294
- if (!Sammy.HashLocationProxy._last_location ||
295
- current_location != Sammy.HashLocationProxy._last_location) {
296
- window.setTimeout(function() {
297
- $(window).trigger('hashchange', [true]);
298
- }, 13);
299
- }
300
- Sammy.HashLocationProxy._last_location = current_location;
301
- };
302
- hashCheck();
303
- Sammy.HashLocationProxy._interval = window.setInterval(hashCheck, every);
304
- }
305
- }
306
- };
307
-
308
-
309
- // Sammy.Application is the Base prototype for defining 'applications'.
310
- // An 'application' is a collection of 'routes' and bound events that is
311
- // attached to an element when `run()` is called.
312
- // The only argument an 'app_function' is evaluated within the context of the application.
313
- Sammy.Application = function(app_function) {
314
- var app = this;
315
- this.routes = {};
316
- this.listeners = new Sammy.Object({});
317
- this.arounds = [];
318
- this.befores = [];
319
- // generate a unique namespace
320
- this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
321
- this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
322
- this.context_prototype.prototype = new Sammy.EventContext();
323
-
324
- if (_isFunction(app_function)) {
325
- app_function.apply(this, [this]);
326
- }
327
- // set the location proxy if not defined to the default (HashLocationProxy)
328
- if (!this._location_proxy) {
329
- this.setLocationProxy(new Sammy.HashLocationProxy(this, this.run_interval_every));
330
- }
331
- if (this.debug) {
332
- this.bindToAllEvents(function(e, data) {
333
- app.log(app.toString(), e.cleaned_type, data || {});
334
- });
335
- }
336
- };
337
-
338
- Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
339
-
340
- // the four route verbs
341
- ROUTE_VERBS: ['get','post','put','delete'],
342
-
343
- // An array of the default events triggered by the
344
- // application during its lifecycle
345
- APP_EVENTS: ['run',
346
- 'unload',
347
- 'lookup-route',
348
- 'run-route',
349
- 'route-found',
350
- 'event-context-before',
351
- 'event-context-after',
352
- 'changed',
353
- 'error',
354
- 'check-form-submission',
355
- 'redirect',
356
- 'location-changed'],
357
-
358
- _last_route: null,
359
- _location_proxy: null,
360
- _running: false,
361
-
362
- // Defines what element the application is bound to. Provide a selector
363
- // (parseable by `jQuery()`) and this will be used by `$element()`
364
- element_selector: 'body',
365
-
366
- // When set to true, logs all of the default events using `log()`
367
- debug: false,
368
-
369
- // When set to true, and the error() handler is not overriden, will actually
370
- // raise JS errors in routes (500) and when routes can't be found (404)
371
- raise_errors: false,
372
-
373
- // The time in milliseconds that the URL is queried for changes
374
- run_interval_every: 50,
375
-
376
- // The default template engine to use when using `partial()` in an
377
- // `EventContext`. `template_engine` can either be a string that
378
- // corresponds to the name of a method/helper on EventContext or it can be a function
379
- // that takes two arguments, the content of the unrendered partial and an optional
380
- // JS object that contains interpolation data. Template engine is only called/refered
381
- // to if the extension of the partial is null or unknown. See `partial()`
382
- // for more information
383
- template_engine: null,
384
-
385
- // //=> Sammy.Application: body
386
- toString: function() {
387
- return 'Sammy.Application:' + this.element_selector;
388
- },
389
-
390
- // returns a jQuery object of the Applications bound element.
391
- $element: function(selector) {
392
- return selector ? $(this.element_selector).find(selector) : $(this.element_selector);
393
- },
394
-
395
- // `use()` is the entry point for including Sammy plugins.
396
- // The first argument to use should be a function() that is evaluated
397
- // in the context of the current application, just like the `app_function`
398
- // argument to the `Sammy.Application` constructor.
399
- //
400
- // Any additional arguments are passed to the app function sequentially.
401
- //
402
- // For much more detail about plugins, check out:
403
- // http://code.quirkey.com/sammy/doc/plugins.html
404
- //
405
- // ### Example
406
- //
407
- // var MyPlugin = function(app, prepend) {
408
- //
409
- // this.helpers({
410
- // myhelper: function(text) {
411
- // alert(prepend + " " + text);
412
- // }
413
- // });
414
- //
415
- // };
416
- //
417
- // var app = $.sammy(function() {
418
- //
419
- // this.use(MyPlugin, 'This is my plugin');
420
- //
421
- // this.get('#/', function() {
422
- // this.myhelper('and dont you forget it!');
423
- // //=> Alerts: This is my plugin and dont you forget it!
424
- // });
425
- //
426
- // });
427
- //
428
- // If plugin is passed as a string it assumes your are trying to load
429
- // Sammy."Plugin". This is the prefered way of loading core Sammy plugins
430
- // as it allows for better error-messaging.
431
- //
432
- // ### Example
433
- //
434
- // $.sammy(function() {
435
- // this.use('Mustache'); //=> Sammy.Mustache
436
- // this.use('Storage'); //=> Sammy.Storage
437
- // });
438
- //
439
- use: function() {
440
- // flatten the arguments
441
- var args = _makeArray(arguments),
442
- plugin = args.shift(),
443
- plugin_name = plugin || '';
444
- try {
445
- args.unshift(this);
446
- if (typeof plugin == 'string') {
447
- plugin_name = 'Sammy.' + plugin;
448
- plugin = Sammy[plugin];
449
- }
450
- plugin.apply(this, args);
451
- } catch(e) {
452
- if (typeof plugin === 'undefined') {
453
- this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
454
- } else if (!_isFunction(plugin)) {
455
- this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
456
- } else {
457
- this.error("Plugin Error", e);
458
- }
459
- }
460
- return this;
461
- },
462
-
463
- // Sets the location proxy for the current app. By default this is set to
464
- // a new `Sammy.HashLocationProxy` on initialization. However, you can set
465
- // the location_proxy inside you're app function to give your app a custom
466
- // location mechanism. See `Sammy.HashLocationProxy` and `Sammy.DataLocationProxy`
467
- // for examples.
468
- //
469
- // `setLocationProxy()` takes an initialized location proxy.
470
- //
471
- // ### Example
472
- //
473
- // // to bind to data instead of the default hash;
474
- // var app = $.sammy(function() {
475
- // this.setLocationProxy(new Sammy.DataLocationProxy(this));
476
- // });
477
- //
478
- setLocationProxy: function(new_proxy) {
479
- var original_proxy = this._location_proxy;
480
- this._location_proxy = new_proxy;
481
- if (this.isRunning()) {
482
- if (original_proxy) {
483
- // if there is already a location proxy, unbind it.
484
- original_proxy.unbind();
485
- }
486
- this._location_proxy.bind();
487
- }
488
- },
489
-
490
- // `route()` is the main method for defining routes within an application.
491
- // For great detail on routes, check out: http://code.quirkey.com/sammy/doc/routes.html
492
- //
493
- // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
494
- //
495
- // ### Arguments
496
- //
497
- // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
498
- // of the ROUTE_VERBS. If only two arguments are passed,
499
- // the first argument is the path, the second is the callback and the verb
500
- // is assumed to be 'any'.
501
- // * `path` A Regexp or a String representing the path to match to invoke this verb.
502
- // * `callback` A Function that is called/evaluated whent the route is run see: `runRoute()`.
503
- // It is also possible to pass a string as the callback, which is looked up as the name
504
- // of a method on the application.
505
- //
506
- route: function(verb, path, callback) {
507
- var app = this, param_names = [], add_route, path_match;
508
-
509
- // if the method signature is just (path, callback)
510
- // assume the verb is 'any'
511
- if (!callback && _isFunction(path)) {
512
- path = verb;
513
- callback = path;
514
- verb = 'any';
515
- }
516
-
517
- verb = verb.toLowerCase(); // ensure verb is lower case
518
-
519
- // if path is a string turn it into a regex
520
- if (path.constructor == String) {
521
-
522
- // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
523
- // which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params
524
- // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
525
- PATH_NAME_MATCHER.lastIndex = 0;
526
-
527
- // find the names
528
- while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
529
- param_names.push(path_match[1]);
530
- }
531
- // replace with the path replacement
532
- path = new RegExp("^" + path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
533
- }
534
- // lookup callback
535
- if (typeof callback == 'string') {
536
- callback = app[callback];
537
- }
538
-
539
- add_route = function(with_verb) {
540
- var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
541
- // add route to routes array
542
- app.routes[with_verb] = app.routes[with_verb] || [];
543
- // place routes in order of definition
544
- app.routes[with_verb].push(r);
545
- };
546
-
547
- if (verb === 'any') {
548
- $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
549
- } else {
550
- add_route(verb);
551
- }
552
-
553
- // return the app
554
- return this;
555
- },
556
-
557
- // Alias for route('get', ...)
558
- get: _routeWrapper('get'),
559
-
560
- // Alias for route('post', ...)
561
- post: _routeWrapper('post'),
562
-
563
- // Alias for route('put', ...)
564
- put: _routeWrapper('put'),
565
-
566
- // Alias for route('delete', ...)
567
- del: _routeWrapper('delete'),
568
-
569
- // Alias for route('any', ...)
570
- any: _routeWrapper('any'),
571
-
572
- // `mapRoutes` takes an array of arrays, each array being passed to route()
573
- // as arguments, this allows for mass definition of routes. Another benefit is
574
- // this makes it possible/easier to load routes via remote JSON.
575
- //
576
- // ### Example
577
- //
578
- // var app = $.sammy(function() {
579
- //
580
- // this.mapRoutes([
581
- // ['get', '#/', function() { this.log('index'); }],
582
- // // strings in callbacks are looked up as methods on the app
583
- // ['post', '#/create', 'addUser'],
584
- // // No verb assumes 'any' as the verb
585
- // [/dowhatever/, function() { this.log(this.verb, this.path)}];
586
- // ]);
587
- // })
588
- //
589
- mapRoutes: function(route_array) {
590
- var app = this;
591
- $.each(route_array, function(i, route_args) {
592
- app.route.apply(app, route_args);
593
- });
594
- return this;
595
- },
596
-
597
- // A unique event namespace defined per application.
598
- // All events bound with `bind()` are automatically bound within this space.
599
- eventNamespace: function() {
600
- return ['sammy-app', this.namespace].join('-');
601
- },
602
-
603
- // Works just like `jQuery.fn.bind()` with a couple noteable differences.
604
- //
605
- // * It binds all events to the application element
606
- // * All events are bound within the `eventNamespace()`
607
- // * Events are not actually bound until the application is started with `run()`
608
- // * callbacks are evaluated within the context of a Sammy.EventContext
609
- //
610
- // See http://code.quirkey.com/sammy/docs/events.html for more info.
611
- //
612
- bind: function(name, data, callback) {
613
- var app = this;
614
- // build the callback
615
- // if the arity is 2, callback is the second argument
616
- if (typeof callback == 'undefined') { callback = data; }
617
- var listener_callback = function() {
618
- // pull off the context from the arguments to the callback
619
- var e, context, data;
620
- e = arguments[0];
621
- data = arguments[1];
622
- if (data && data.context) {
623
- context = data.context;
624
- delete data.context;
625
- } else {
626
- context = new app.context_prototype(app, 'bind', e.type, data, e.target);
627
- }
628
- e.cleaned_type = e.type.replace(app.eventNamespace(), '');
629
- callback.apply(context, [e, data]);
630
- };
631
-
632
- // it could be that the app element doesnt exist yet
633
- // so attach to the listeners array and then run()
634
- // will actually bind the event.
635
- if (!this.listeners[name]) { this.listeners[name] = []; }
636
- this.listeners[name].push(listener_callback);
637
- if (this.isRunning()) {
638
- // if the app is running
639
- // *actually* bind the event to the app element
640
- this._listen(name, listener_callback);
641
- }
642
- return this;
643
- },
644
-
645
- // Triggers custom events defined with `bind()`
646
- //
647
- // ### Arguments
648
- //
649
- // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
650
- // * `data` An optional Object that can be passed to the bound callback.
651
- // * `context` An optional context/Object in which to execute the bound callback.
652
- // If no context is supplied a the context is a new `Sammy.EventContext`
653
- //
654
- trigger: function(name, data) {
655
- this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
656
- return this;
657
- },
658
-
659
- // Reruns the current route
660
- refresh: function() {
661
- this.last_location = null;
662
- this.trigger('location-changed');
663
- return this;
664
- },
665
-
666
- // Takes a single callback that is pushed on to a stack.
667
- // Before any route is run, the callbacks are evaluated in order within
668
- // the current `Sammy.EventContext`
669
- //
670
- // If any of the callbacks explicitly return false, execution of any
671
- // further callbacks and the route itself is halted.
672
- //
673
- // You can also provide a set of options that will define when to run this
674
- // before based on the route it proceeds.
675
- //
676
- // ### Example
677
- //
678
- // var app = $.sammy(function() {
679
- //
680
- // // will run at #/route but not at #/
681
- // this.before('#/route', function() {
682
- // //...
683
- // });
684
- //
685
- // // will run at #/ but not at #/route
686
- // this.before({except: {path: '#/route'}}, function() {
687
- // this.log('not before #/route');
688
- // });
689
- //
690
- // this.get('#/', function() {});
691
- //
692
- // this.get('#/route', function() {});
693
- //
694
- // });
695
- //
696
- // See `contextMatchesOptions()` for a full list of supported options
697
- //
698
- before: function(options, callback) {
699
- if (_isFunction(options)) {
700
- callback = options;
701
- options = {};
702
- }
703
- this.befores.push([options, callback]);
704
- return this;
705
- },
706
-
707
- // A shortcut for binding a callback to be run after a route is executed.
708
- // After callbacks have no guarunteed order.
709
- after: function(callback) {
710
- return this.bind('event-context-after', callback);
711
- },
712
-
713
-
714
- // Adds an around filter to the application. around filters are functions
715
- // that take a single argument `callback` which is the entire route
716
- // execution path wrapped up in a closure. This means you can decide whether
717
- // or not to proceed with execution by not invoking `callback` or,
718
- // more usefuly wrapping callback inside the result of an asynchronous execution.
719
- //
720
- // ### Example
721
- //
722
- // The most common use case for around() is calling a _possibly_ async function
723
- // and executing the route within the functions callback:
724
- //
725
- // var app = $.sammy(function() {
726
- //
727
- // var current_user = false;
728
- //
729
- // function checkLoggedIn(callback) {
730
- // // /session returns a JSON representation of the logged in user
731
- // // or an empty object
732
- // if (!current_user) {
733
- // $.getJSON('/session', function(json) {
734
- // if (json.login) {
735
- // // show the user as logged in
736
- // current_user = json;
737
- // // execute the route path
738
- // callback();
739
- // } else {
740
- // // show the user as not logged in
741
- // current_user = false;
742
- // // the context of aroundFilters is an EventContext
743
- // this.redirect('#/login');
744
- // }
745
- // });
746
- // } else {
747
- // // execute the route path
748
- // callback();
749
- // }
750
- // };
751
- //
752
- // this.around(checkLoggedIn);
753
- //
754
- // });
755
- //
756
- around: function(callback) {
757
- this.arounds.push(callback);
758
- return this;
759
- },
760
-
761
- // Returns `true` if the current application is running.
762
- isRunning: function() {
763
- return this._running;
764
- },
765
-
766
- // Helpers extends the EventContext prototype specific to this app.
767
- // This allows you to define app specific helper functions that can be used
768
- // whenever you're inside of an event context (templates, routes, bind).
769
- //
770
- // ### Example
771
- //
772
- // var app = $.sammy(function() {
773
- //
774
- // helpers({
775
- // upcase: function(text) {
776
- // return text.toString().toUpperCase();
777
- // }
778
- // });
779
- //
780
- // get('#/', function() { with(this) {
781
- // // inside of this context I can use the helpers
782
- // $('#main').html(upcase($('#main').text());
783
- // }});
784
- //
785
- // });
786
- //
787
- //
788
- // ### Arguments
789
- //
790
- // * `extensions` An object collection of functions to extend the context.
791
- //
792
- helpers: function(extensions) {
793
- $.extend(this.context_prototype.prototype, extensions);
794
- return this;
795
- },
796
-
797
- // Helper extends the event context just like `helpers()` but does it
798
- // a single method at a time. This is especially useful for dynamically named
799
- // helpers
800
- //
801
- // ### Example
802
- //
803
- // // Trivial example that adds 3 helper methods to the context dynamically
804
- // var app = $.sammy(function(app) {
805
- //
806
- // $.each([1,2,3], function(i, num) {
807
- // app.helper('helper' + num, function() {
808
- // this.log("I'm helper number " + num);
809
- // });
810
- // });
811
- //
812
- // this.get('#/', function() {
813
- // this.helper2(); //=> I'm helper number 2
814
- // });
815
- // });
816
- //
817
- // ### Arguments
818
- //
819
- // * `name` The name of the method
820
- // * `method` The function to be added to the prototype at `name`
821
- //
822
- helper: function(name, method) {
823
- this.context_prototype.prototype[name] = method;
824
- return this;
825
- },
826
-
827
- // Actually starts the application's lifecycle. `run()` should be invoked
828
- // within a document.ready block to ensure the DOM exists before binding events, etc.
829
- //
830
- // ### Example
831
- //
832
- // var app = $.sammy(function() { ... }); // your application
833
- // $(function() { // document.ready
834
- // app.run();
835
- // });
836
- //
837
- // ### Arguments
838
- //
839
- // * `start_url` Optionally, a String can be passed which the App will redirect to
840
- // after the events/routes have been bound.
841
- run: function(start_url) {
842
- if (this.isRunning()) { return false; }
843
- var app = this;
844
-
845
- // actually bind all the listeners
846
- $.each(this.listeners.toHash(), function(name, callbacks) {
847
- $.each(callbacks, function(i, listener_callback) {
848
- app._listen(name, listener_callback);
849
- });
850
- });
851
-
852
- this.trigger('run', {start_url: start_url});
853
- this._running = true;
854
- // set last location
855
- this.last_location = null;
856
- if (this.getLocation() == '' && typeof start_url != 'undefined') {
857
- this.setLocation(start_url);
858
- }
859
- // check url
860
- this._checkLocation();
861
- this._location_proxy.bind();
862
- this.bind('location-changed', function() {
863
- app._checkLocation();
864
- });
865
-
866
- // bind to submit to capture post/put/delete routes
867
- /*
868
- this.bind('submit', function(e) {
869
- var returned = app._checkFormSubmission($(e.target).closest('form'));
870
- return (returned === false) ? e.preventDefault() : false;
871
- });
872
- */
873
-
874
- // bind unload to body unload
875
- $(window).bind('beforeunload', function() {
876
- app.unload();
877
- });
878
-
879
- // trigger html changed
880
- return this.trigger('changed');
881
- },
882
-
883
- // The opposite of `run()`, un-binds all event listeners and intervals
884
- // `run()` Automaticaly binds a `onunload` event to run this when
885
- // the document is closed.
886
- unload: function() {
887
- if (!this.isRunning()) { return false; }
888
- var app = this;
889
- this.trigger('unload');
890
- // clear interval
891
- this._location_proxy.unbind();
892
- // unbind form submits
893
- this.$element().unbind('submit').removeClass(app.eventNamespace());
894
- // unbind all events
895
- $.each(this.listeners.toHash() , function(name, listeners) {
896
- $.each(listeners, function(i, listener_callback) {
897
- app._unlisten(name, listener_callback);
898
- });
899
- });
900
- this._running = false;
901
- return this;
902
- },
903
-
904
- // Will bind a single callback function to every event that is already
905
- // being listened to in the app. This includes all the `APP_EVENTS`
906
- // as well as any custom events defined with `bind()`.
907
- //
908
- // Used internally for debug logging.
909
- bindToAllEvents: function(callback) {
910
- var app = this;
911
- // bind to the APP_EVENTS first
912
- $.each(this.APP_EVENTS, function(i, e) {
913
- app.bind(e, callback);
914
- });
915
- // next, bind to listener names (only if they dont exist in APP_EVENTS)
916
- $.each(this.listeners.keys(true), function(i, name) {
917
- if (app.APP_EVENTS.indexOf(name) == -1) {
918
- app.bind(name, callback);
919
- }
920
- });
921
- return this;
922
- },
923
-
924
- // Returns a copy of the given path with any query string after the hash
925
- // removed.
926
- routablePath: function(path) {
927
- return path.replace(QUERY_STRING_MATCHER, '');
928
- },
929
-
930
- // Given a verb and a String path, will return either a route object or false
931
- // if a matching route can be found within the current defined set.
932
- lookupRoute: function(verb, path) {
933
- var app = this, routed = false;
934
- this.trigger('lookup-route', {verb: verb, path: path});
935
- if (typeof this.routes[verb] != 'undefined') {
936
- $.each(this.routes[verb], function(i, route) {
937
- if (app.routablePath(path).match(route.path)) {
938
- routed = route;
939
- return false;
940
- }
941
- });
942
- }
943
- return routed;
944
- },
945
-
946
- // First, invokes `lookupRoute()` and if a route is found, parses the
947
- // possible URL params and then invokes the route's callback within a new
948
- // `Sammy.EventContext`. If the route can not be found, it calls
949
- // `notFound()`. If `raise_errors` is set to `true` and
950
- // the `error()` has not been overriden, it will throw an actual JS
951
- // error.
952
- //
953
- // You probably will never have to call this directly.
954
- //
955
- // ### Arguments
956
- //
957
- // * `verb` A String for the verb.
958
- // * `path` A String path to lookup.
959
- // * `params` An Object of Params pulled from the URI or passed directly.
960
- //
961
- // ### Returns
962
- //
963
- // Either returns the value returned by the route callback or raises a 404 Not Found error.
964
- //
965
- runRoute: function(verb, path, params, target) {
966
- var app = this,
967
- route = this.lookupRoute(verb, path),
968
- context,
969
- wrapped_route,
970
- arounds,
971
- around,
972
- befores,
973
- before,
974
- callback_args,
975
- path_params,
976
- final_returned;
977
-
978
- this.log('runRoute', [verb, path].join(' '));
979
- this.trigger('run-route', {verb: verb, path: path, params: params});
980
- if (typeof params == 'undefined') { params = {}; }
981
-
982
- $.extend(params, this._parseQueryString(path));
983
-
984
- if (route) {
985
- this.trigger('route-found', {route: route});
986
- // pull out the params from the path
987
- if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
988
- // first match is the full path
989
- path_params.shift();
990
- // for each of the matches
991
- $.each(path_params, function(i, param) {
992
- // if theres a matching param name
993
- if (route.param_names[i]) {
994
- // set the name to the match
995
- params[route.param_names[i]] = _decode(param);
996
- } else {
997
- // initialize 'splat'
998
- if (!params.splat) { params.splat = []; }
999
- params.splat.push(_decode(param));
1000
- }
1001
- });
1002
- }
1003
-
1004
- // set event context
1005
- context = new this.context_prototype(this, verb, path, params, target);
1006
- // ensure arrays
1007
- arounds = this.arounds.slice(0);
1008
- befores = this.befores.slice(0);
1009
- // set the callback args to the context + contents of the splat
1010
- callback_args = [context].concat(params.splat);
1011
- // wrap the route up with the before filters
1012
- wrapped_route = function() {
1013
- var returned;
1014
- while (befores.length > 0) {
1015
- before = befores.shift();
1016
- // check the options
1017
- if (app.contextMatchesOptions(context, before[0])) {
1018
- returned = before[1].apply(context, [context]);
1019
- if (returned === false) { return false; }
1020
- }
1021
- }
1022
- app.last_route = route;
1023
- context.trigger('event-context-before', {context: context});
1024
- returned = route.callback.apply(context, callback_args);
1025
- context.trigger('event-context-after', {context: context});
1026
- return returned;
1027
- };
1028
- $.each(arounds.reverse(), function(i, around) {
1029
- var last_wrapped_route = wrapped_route;
1030
- wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
1031
- });
1032
- try {
1033
- final_returned = wrapped_route();
1034
- } catch(e) {
1035
- this.error(['500 Error', verb, path].join(' '), e);
1036
- }
1037
- return final_returned;
1038
- } else {
1039
- return this.notFound(verb, path);
1040
- }
1041
- },
1042
-
1043
- // Matches an object of options against an `EventContext` like object that
1044
- // contains `path` and `verb` attributes. Internally Sammy uses this
1045
- // for matching `before()` filters against specific options. You can set the
1046
- // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
1047
- // those that match the options.
1048
- //
1049
- // ### Example
1050
- //
1051
- // var app = $.sammy(),
1052
- // context = {verb: 'get', path: '#/mypath'};
1053
- //
1054
- // // match against a path string
1055
- // app.contextMatchesOptions(context, '#/mypath'); //=> true
1056
- // app.contextMatchesOptions(context, '#/otherpath'); //=> false
1057
- // // equivilent to
1058
- // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
1059
- // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
1060
- // // match against a path regexp
1061
- // app.contextMatchesOptions(context, /path/); //=> true
1062
- // app.contextMatchesOptions(context, /^path/); //=> false
1063
- // // match only a verb
1064
- // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
1065
- // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
1066
- // // match all except a verb
1067
- // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
1068
- // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
1069
- // // match all except a path
1070
- // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
1071
- // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
1072
- //
1073
- contextMatchesOptions: function(context, match_options, positive) {
1074
- // empty options always match
1075
- var options = match_options;
1076
- if (typeof options === 'undefined' || options == {}) {
1077
- return true;
1078
- }
1079
- if (typeof positive === 'undefined') {
1080
- positive = true;
1081
- }
1082
- // normalize options
1083
- if (typeof options === 'string' || _isFunction(options.test)) {
1084
- options = {path: options};
1085
- }
1086
- if (options.only) {
1087
- return this.contextMatchesOptions(context, options.only, true);
1088
- } else if (options.except) {
1089
- return this.contextMatchesOptions(context, options.except, false);
1090
- }
1091
- var path_matched = true, verb_matched = true;
1092
- if (options.path) {
1093
- // wierd regexp test
1094
- if (_isFunction(options.path.test)) {
1095
- path_matched = options.path.test(context.path);
1096
- } else {
1097
- path_matched = (options.path.toString() === context.path);
1098
- }
1099
- }
1100
- if (options.verb) {
1101
- verb_matched = options.verb === context.verb;
1102
- }
1103
- return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
1104
- },
1105
-
1106
-
1107
- // Delegates to the `location_proxy` to get the current location.
1108
- // See `Sammy.HashLocationProxy` for more info on location proxies.
1109
- getLocation: function() {
1110
- return this._location_proxy.getLocation();
1111
- },
1112
-
1113
- // Delegates to the `location_proxy` to set the current location.
1114
- // See `Sammy.HashLocationProxy` for more info on location proxies.
1115
- //
1116
- // ### Arguments
1117
- //
1118
- // * `new_location` A new location string (e.g. '#/')
1119
- //
1120
- setLocation: function(new_location) {
1121
- return this._location_proxy.setLocation(new_location);
1122
- },
1123
-
1124
- // Swaps the content of `$element()` with `content`
1125
- // You can override this method to provide an alternate swap behavior
1126
- // for `EventContext.partial()`.
1127
- //
1128
- // ### Example
1129
- //
1130
- // var app = $.sammy(function() {
1131
- //
1132
- // // implements a 'fade out'/'fade in'
1133
- // this.swap = function(content) {
1134
- // this.$element().hide('slow').html(content).show('slow');
1135
- // }
1136
- //
1137
- // get('#/', function() {
1138
- // this.partial('index.html.erb') // will fade out and in
1139
- // });
1140
- //
1141
- // });
1142
- //
1143
- swap: function(content) {
1144
- return this.$element().html(content);
1145
- },
1146
-
1147
- // a simple global cache for templates. Uses the same semantics as
1148
- // `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
1149
- // a persistant storage that lasts beyond the current request.
1150
- templateCache: function(key, value) {
1151
- if (typeof value != 'undefined') {
1152
- return _template_cache[key] = value;
1153
- } else {
1154
- return _template_cache[key];
1155
- }
1156
- },
1157
-
1158
- // clear the templateCache
1159
- clearTemplateCache: function() {
1160
- return _template_cache = {};
1161
- },
1162
-
1163
- // This thows a '404 Not Found' error by invoking `error()`.
1164
- // Override this method or `error()` to provide custom
1165
- // 404 behavior (i.e redirecting to / or showing a warning)
1166
- notFound: function(verb, path) {
1167
- var ret = this.error(['404 Not Found', verb, path].join(' '));
1168
- return (verb === 'get') ? ret : true;
1169
- },
1170
-
1171
- // The base error handler takes a string `message` and an `Error`
1172
- // object. If `raise_errors` is set to `true` on the app level,
1173
- // this will re-throw the error to the browser. Otherwise it will send the error
1174
- // to `log()`. Override this method to provide custom error handling
1175
- // e.g logging to a server side component or displaying some feedback to the
1176
- // user.
1177
- error: function(message, original_error) {
1178
- if (!original_error) { original_error = new Error(); }
1179
- original_error.message = [message, original_error.message].join(' ');
1180
- this.trigger('error', {message: original_error.message, error: original_error});
1181
- if (this.raise_errors) {
1182
- throw(original_error);
1183
- } else {
1184
- this.log(original_error.message, original_error);
1185
- }
1186
- },
1187
-
1188
- _checkLocation: function() {
1189
- var location, returned;
1190
- // get current location
1191
- location = this.getLocation();
1192
- // compare to see if hash has changed
1193
- if (!this.last_location || this.last_location[0] != 'get' || this.last_location[1] != location) {
1194
- // reset last location
1195
- this.last_location = ['get', location];
1196
- // lookup route for current hash
1197
- returned = this.runRoute('get', location);
1198
- }
1199
- return returned;
1200
- },
1201
-
1202
- _getFormVerb: function(form) {
1203
- var $form = $(form), verb, $_method;
1204
- $_method = $form.find('input[name="_method"]');
1205
- if ($_method.length > 0) { verb = $_method.val(); }
1206
- if (!verb) { verb = $form[0].getAttribute('method'); }
1207
- return $.trim(verb.toString().toLowerCase());
1208
- },
1209
-
1210
- _checkFormSubmission: function(form) {
1211
- var $form, path, verb, params, returned;
1212
- this.trigger('check-form-submission', {form: form});
1213
- $form = $(form);
1214
- path = $form.attr('action');
1215
- verb = this._getFormVerb($form);
1216
- if (!verb || verb == '') { verb = 'get'; }
1217
- this.log('_checkFormSubmission', $form, path, verb);
1218
- if (verb === 'get') {
1219
- this.setLocation(path + '?' + this._serializeFormParams($form));
1220
- returned = false;
1221
- } else {
1222
- params = $.extend({}, this._parseFormParams($form));
1223
- returned = this.runRoute(verb, path, params, form.get(0));
1224
- };
1225
- return (typeof returned == 'undefined') ? false : returned;
1226
- },
1227
-
1228
- _serializeFormParams: function($form) {
1229
- var queryString = "",
1230
- fields = $form.serializeArray(),
1231
- i;
1232
- if (fields.length > 0) {
1233
- queryString = this._encodeFormPair(fields[0].name, fields[0].value);
1234
- for (i = 1; i < fields.length; i++) {
1235
- queryString = queryString + "&" + this._encodeFormPair(fields[i].name, fields[i].value);
1236
- }
1237
- }
1238
- return queryString;
1239
- },
1240
-
1241
- _encodeFormPair: function(name, value){
1242
- return _encode(name) + "=" + _encode(value);
1243
- },
1244
-
1245
- _parseFormParams: function($form) {
1246
- var params = {},
1247
- form_fields = $form.serializeArray(),
1248
- i;
1249
- for (i = 0; i < form_fields.length; i++) {
1250
- params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
1251
- }
1252
- return params;
1253
- },
1254
-
1255
- _parseQueryString: function(path) {
1256
- var params = {}, parts, pairs, pair, i;
1257
-
1258
- parts = path.match(QUERY_STRING_MATCHER);
1259
- if (parts) {
1260
- pairs = parts[1].split('&');
1261
- for (i = 0; i < pairs.length; i++) {
1262
- pair = pairs[i].split('=');
1263
- params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1]));
1264
- }
1265
- }
1266
- return params;
1267
- },
1268
-
1269
- _parseParamPair: function(params, key, value) {
1270
- if (params[key]) {
1271
- if (_isArray(params[key])) {
1272
- params[key].push(value);
1273
- } else {
1274
- params[key] = [params[key], value];
1275
- }
1276
- } else {
1277
- params[key] = value;
1278
- }
1279
- return params;
1280
- },
1281
-
1282
- _listen: function(name, callback) {
1283
- return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
1284
- },
1285
-
1286
- _unlisten: function(name, callback) {
1287
- return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
1288
- }
1289
-
1290
- });
1291
-
1292
- // `Sammy.RenderContext` is an object that makes sequential template loading,
1293
- // rendering and interpolation seamless even when dealing with asyncronous
1294
- // operations.
1295
- //
1296
- // `RenderContext` objects are not usually created directly, rather they are
1297
- // instatiated from an `Sammy.EventContext` by using `render()`, `load()` or
1298
- // `partial()` which all return `RenderContext` objects.
1299
- //
1300
- // `RenderContext` methods always returns a modified `RenderContext`
1301
- // for chaining (like jQuery itself).
1302
- //
1303
- // The core magic is in the `then()` method which puts the callback passed as
1304
- // an argument into a queue to be executed once the previous callback is complete.
1305
- // All the methods of `RenderContext` are wrapped in `then()` which allows you
1306
- // to queue up methods by chaining, but maintaing a guarunteed execution order
1307
- // even with remote calls to fetch templates.
1308
- //
1309
- Sammy.RenderContext = function(event_context) {
1310
- this.event_context = event_context;
1311
- this.callbacks = [];
1312
- this.previous_content = null;
1313
- this.content = null;
1314
- this.next_engine = false;
1315
- this.waiting = false;
1316
- };
1317
-
1318
- Sammy.RenderContext.prototype = $.extend({}, Sammy.Object.prototype, {
1319
-
1320
- // The "core" of the `RenderContext` object, adds the `callback` to the
1321
- // queue. If the context is `waiting` (meaning an async operation is happening)
1322
- // then the callback will be executed in order, once the other operations are
1323
- // complete. If there is no currently executing operation, the `callback`
1324
- // is executed immediately.
1325
- //
1326
- // The value returned from the callback is stored in `content` for the
1327
- // subsiquent operation. If you return `false`, the queue will pause, and
1328
- // the next callback in the queue will not be executed until `next()` is
1329
- // called. This allows for the guarunteed order of execution while working
1330
- // with async operations.
1331
- //
1332
- // If then() is passed a string instead of a function, the string is looked
1333
- // up as a helper method on the event context.
1334
- //
1335
- // ### Example
1336
- //
1337
- // this.get('#/', function() {
1338
- // // initialize the RenderContext
1339
- // // Even though `load()` executes async, the next `then()`
1340
- // // wont execute until the load finishes
1341
- // this.load('myfile.txt')
1342
- // .then(function(content) {
1343
- // // the first argument to then is the content of the
1344
- // // prev operation
1345
- // $('#main').html(content);
1346
- // });
1347
- // });
1348
- //
1349
- then: function(callback) {
1350
- if (!_isFunction(callback)) {
1351
- // if a string is passed to then, assume we want to call
1352
- // a helper on the event context in its context
1353
- if (typeof callback === 'string' && callback in this.event_context) {
1354
- var helper = this.event_context[callback];
1355
- callback = function(content) {
1356
- return helper.apply(this.event_context, [content]);
1357
- };
1358
- } else {
1359
- return this;
1360
- }
1361
- }
1362
- var context = this;
1363
- if (this.waiting) {
1364
- this.callbacks.push(callback);
1365
- } else {
1366
- this.wait();
1367
- window.setTimeout(function() {
1368
- var returned = callback.apply(context, [context.content, context.previous_content]);
1369
- if (returned !== false) {
1370
- context.next(returned);
1371
- }
1372
- }, 13);
1373
- }
1374
- return this;
1375
- },
1376
-
1377
- // Pause the `RenderContext` queue. Combined with `next()` allows for async
1378
- // operations.
1379
- //
1380
- // ### Example
1381
- //
1382
- // this.get('#/', function() {
1383
- // this.load('mytext.json')
1384
- // .then(function(content) {
1385
- // var context = this,
1386
- // data = JSON.parse(content);
1387
- // // pause execution
1388
- // context.wait();
1389
- // // post to a url
1390
- // $.post(data.url, {}, function(response) {
1391
- // context.next(JSON.parse(response));
1392
- // });
1393
- // })
1394
- // .then(function(data) {
1395
- // // data is json from the previous post
1396
- // $('#message').text(data.status);
1397
- // });
1398
- // });
1399
- wait: function() {
1400
- this.waiting = true;
1401
- },
1402
-
1403
- // Resume the queue, setting `content` to be used in the next operation.
1404
- // See `wait()` for an example.
1405
- next: function(content) {
1406
- this.waiting = false;
1407
- if (typeof content !== 'undefined') {
1408
- this.previous_content = this.content;
1409
- this.content = content;
1410
- }
1411
- if (this.callbacks.length > 0) {
1412
- this.then(this.callbacks.shift());
1413
- }
1414
- },
1415
-
1416
- // Load a template into the context.
1417
- // The `location` can either be a string specifiying the remote path to the
1418
- // file, a jQuery object, or a DOM element.
1419
- //
1420
- // No interpolation happens by default, the content is stored in
1421
- // `content`.
1422
- //
1423
- // In the case of a path, unless the option `{cache: false}` is passed the
1424
- // data is stored in the app's `templateCache()`.
1425
- //
1426
- // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
1427
- // This is useful for nesting templates as part of the initial page load wrapped
1428
- // in invisible elements or `<script>` tags. With template paths, the template
1429
- // engine is looked up by the extension. For DOM/jQuery embedded templates,
1430
- // this isnt possible, so there are a couple of options:
1431
- //
1432
- // * pass an `{engine:}` option.
1433
- // * define the engine in the `data-engine` attribute of the passed node.
1434
- // * just store the raw template data and use `interpolate()` manually
1435
- //
1436
- // If a `callback` is passed it is executed after the template load.
1437
- load: function(location, options, callback) {
1438
- var context = this;
1439
- return this.then(function() {
1440
- var should_cache, cached, is_json, location_array;
1441
- if (_isFunction(options)) {
1442
- callback = options;
1443
- options = {};
1444
- } else {
1445
- options = $.extend({}, options);
1446
- }
1447
- if (callback) { this.then(callback); }
1448
- if (typeof location === 'string') {
1449
- // it's a path
1450
- is_json = (location.match(/\.json$/) || options.json);
1451
- should_cache = ((is_json && options.cache === true) || options.cache !== false);
1452
- context.next_engine = context.event_context.engineFor(location);
1453
- delete options.cache;
1454
- delete options.json;
1455
- if (options.engine) {
1456
- context.next_engine = options.engine;
1457
- delete options.engine;
1458
- }
1459
- if (should_cache && (cached = this.event_context.app.templateCache(location))) {
1460
- return cached;
1461
- }
1462
- this.wait();
1463
- $.ajax($.extend({
1464
- url: location,
1465
- data: {},
1466
- dataType: is_json ? 'json' : null,
1467
- type: 'get',
1468
- success: function(data) {
1469
- if (should_cache) {
1470
- context.event_context.app.templateCache(location, data);
1471
- }
1472
- context.next(data);
1473
- }
1474
- }, options));
1475
- return false;
1476
- } else {
1477
- // it's a dom/jQuery
1478
- if (location.nodeType) {
1479
- return location.innerHTML;
1480
- }
1481
- if (location.selector) {
1482
- // it's a jQuery
1483
- context.next_engine = location.attr('data-engine');
1484
- if (options.clone === false) {
1485
- return location.remove()[0].innerHTML.toString();
1486
- } else {
1487
- return location[0].innerHTML.toString();
1488
- }
1489
- }
1490
- }
1491
- });
1492
- },
1493
-
1494
- // `load()` a template and then `interpolate()` it with data.
1495
- //
1496
- // ### Example
1497
- //
1498
- // this.get('#/', function() {
1499
- // this.render('mytemplate.template', {name: 'test'});
1500
- // });
1501
- //
1502
- render: function(location, data, callback) {
1503
- if (_isFunction(location) && !data) {
1504
- return this.then(location);
1505
- } else {
1506
- if (!data && this.content) { data = this.content; }
1507
- return this.load(location)
1508
- .interpolate(data, location)
1509
- .then(callback);
1510
- }
1511
- },
1512
-
1513
- // `render()` the the `location` with `data` and then `swap()` the
1514
- // app's `$element` with the rendered content.
1515
- partial: function(location, data) {
1516
- return this.render(location, data).swap();
1517
- },
1518
-
1519
- // defers the call of function to occur in order of the render queue.
1520
- // The function can accept any number of arguments as long as the last
1521
- // argument is a callback function. This is useful for putting arbitrary
1522
- // asynchronous functions into the queue. The content passed to the
1523
- // callback is passed as `content` to the next item in the queue.
1524
- //
1525
- // === Example
1526
- //
1527
- // this.send($.getJSON, '/app.json')
1528
- // .then(function(json) {
1529
- // $('#message).text(json['message']);
1530
- // });
1531
- //
1532
- //
1533
- send: function() {
1534
- var context = this,
1535
- args = _makeArray(arguments),
1536
- fun = args.shift();
1537
-
1538
- if (_isArray(args[0])) { args = args[0]; }
1539
-
1540
- return this.then(function(content) {
1541
- args.push(function(response) { context.next(response); });
1542
- context.wait();
1543
- fun.apply(fun, args);
1544
- return false;
1545
- });
1546
- },
1547
-
1548
- // itterates over an array, applying the callback for each item item. the
1549
- // callback takes the same style of arguments as `jQuery.each()` (index, item).
1550
- // The return value of each callback is collected as a single string and stored
1551
- // as `content` to be used in the next iteration of the `RenderContext`.
1552
- collect: function(array, callback, now) {
1553
- var context = this;
1554
- var coll = function() {
1555
- if (_isFunction(array)) {
1556
- callback = array;
1557
- array = this.content;
1558
- }
1559
- var contents = [], doms = false;
1560
- $.each(array, function(i, item) {
1561
- var returned = callback.apply(context, [i, item]);
1562
- if (returned.jquery && returned.length == 1) {
1563
- returned = returned[0];
1564
- doms = true;
1565
- }
1566
- contents.push(returned);
1567
- return returned;
1568
- });
1569
- return doms ? contents : contents.join('');
1570
- };
1571
- return now ? coll() : this.then(coll);
1572
- },
1573
-
1574
- // loads a template, and then interpolates it for each item in the `data`
1575
- // array. If a callback is passed, it will call the callback with each
1576
- // item in the array _after_ interpolation
1577
- renderEach: function(location, name, data, callback) {
1578
- if (_isArray(name)) {
1579
- callback = data;
1580
- data = name;
1581
- name = null;
1582
- }
1583
- return this.load(location).then(function(content) {
1584
- var rctx = this;
1585
- if (!data) {
1586
- data = _isArray(this.previous_content) ? this.previous_content : [];
1587
- }
1588
- if (callback) {
1589
- $.each(data, function(i, value) {
1590
- var idata = {}, engine = this.next_engine || location;
1591
- name ? (idata[name] = value) : (idata = value);
1592
- callback(value, rctx.event_context.interpolate(content, idata, engine));
1593
- });
1594
- } else {
1595
- return this.collect(data, function(i, value) {
1596
- var idata = {}, engine = this.next_engine || location;
1597
- name ? (idata[name] = value) : (idata = value);
1598
- return this.event_context.interpolate(content, idata, engine);
1599
- }, true);
1600
- }
1601
- });
1602
- },
1603
-
1604
- // uses the previous loaded `content` and the `data` object to interpolate
1605
- // a template. `engine` defines the templating/interpolation method/engine
1606
- // that should be used. If `engine` is not passed, the `next_engine` is
1607
- // used. If `retain` is `true`, the final interpolated data is appended to
1608
- // the `previous_content` instead of just replacing it.
1609
- interpolate: function(data, engine, retain) {
1610
- var context = this;
1611
- return this.then(function(content, prev) {
1612
- if (!data && prev) { data = prev; }
1613
- if (this.next_engine) {
1614
- engine = this.next_engine;
1615
- this.next_engine = false;
1616
- }
1617
- var rendered = context.event_context.interpolate(content, data, engine);
1618
- return retain ? prev + rendered : rendered;
1619
- });
1620
- },
1621
-
1622
- // executes `EventContext#swap()` with the `content`
1623
- swap: function() {
1624
- return this.then(function(content) {
1625
- this.event_context.swap(content);
1626
- }).trigger('changed', {});
1627
- },
1628
-
1629
- // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
1630
- appendTo: function(selector) {
1631
- return this.then(function(content) {
1632
- $(selector).append(content);
1633
- }).trigger('changed', {});
1634
- },
1635
-
1636
- // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
1637
- prependTo: function(selector) {
1638
- return this.then(function(content) {
1639
- $(selector).prepend(content);
1640
- }).trigger('changed', {});
1641
- },
1642
-
1643
- // Replaces the `$(selector)` using `html()` with the previously loaded
1644
- // `content`
1645
- replace: function(selector) {
1646
- return this.then(function(content) {
1647
- $(selector).html(content);
1648
- }).trigger('changed', {});
1649
- },
1650
-
1651
- // trigger the event in the order of the event context. Same semantics
1652
- // as `Sammy.EventContext#trigger()`. If data is ommitted, `content`
1653
- // is sent as `{content: content}`
1654
- trigger: function(name, data) {
1655
- return this.then(function(content) {
1656
- if (typeof data == 'undefined') { data = {content: content}; }
1657
- this.event_context.trigger(name, data);
1658
- });
1659
- }
1660
-
1661
- });
1662
-
1663
- // `Sammy.EventContext` objects are created every time a route is run or a
1664
- // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
1665
- // This within these callbacks the special methods of `EventContext` are available.
1666
- //
1667
- // ### Example
1668
- //
1669
- // $.sammy(function() {
1670
- // // The context here is this Sammy.Application
1671
- // this.get('#/:name', function() {
1672
- // // The context here is a new Sammy.EventContext
1673
- // if (this.params['name'] == 'sammy') {
1674
- // this.partial('name.html.erb', {name: 'Sammy'});
1675
- // } else {
1676
- // this.redirect('#/somewhere-else')
1677
- // }
1678
- // });
1679
- // });
1680
- //
1681
- // Initialize a new EventContext
1682
- //
1683
- // ### Arguments
1684
- //
1685
- // * `app` The `Sammy.Application` this event is called within.
1686
- // * `verb` The verb invoked to run this context/route.
1687
- // * `path` The string path invoked to run this context/route.
1688
- // * `params` An Object of optional params to pass to the context. Is converted
1689
- // to a `Sammy.Object`.
1690
- // * `target` a DOM element that the event that holds this context originates
1691
- // from. For post, put and del routes, this is the form element that triggered
1692
- // the route.
1693
- //
1694
- Sammy.EventContext = function(app, verb, path, params, target) {
1695
- this.app = app;
1696
- this.verb = verb;
1697
- this.path = path;
1698
- this.params = new Sammy.Object(params);
1699
- this.target = target;
1700
- };
1701
-
1702
- Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
1703
-
1704
- // A shortcut to the app's `$element()`
1705
- $element: function() {
1706
- return this.app.$element(_makeArray(arguments).shift());
1707
- },
1708
-
1709
- // Look up a templating engine within the current app and context.
1710
- // `engine` can be one of the following:
1711
- //
1712
- // * a function: should conform to `function(content, data) { return interploated; }`
1713
- // * a template path: 'template.ejs', looks up the extension to match to
1714
- // the `ejs()` helper
1715
- // * a string referering to the helper: "mustache" => `mustache()`
1716
- //
1717
- // If no engine is found, use the app's default `template_engine`
1718
- //
1719
- engineFor: function(engine) {
1720
- var context = this, engine_match;
1721
- // if path is actually an engine function just return it
1722
- if (_isFunction(engine)) { return engine; }
1723
- // lookup engine name by path extension
1724
- engine = (engine || context.app.template_engine).toString();
1725
- if ((engine_match = engine.match(/\.([^\.]+)$/))) {
1726
- engine = engine_match[1];
1727
- }
1728
- // set the engine to the default template engine if no match is found
1729
- if (engine && _isFunction(context[engine])) {
1730
- return context[engine];
1731
- }
1732
-
1733
- if (context.app.template_engine) {
1734
- return this.engineFor(context.app.template_engine);
1735
- }
1736
- return function(content, data) { return content; };
1737
- },
1738
-
1739
- // using the template `engine` found with `engineFor()`, interpolate the
1740
- // `data` into `content`
1741
- interpolate: function(content, data, engine) {
1742
- return this.engineFor(engine).apply(this, [content, data]);
1743
- },
1744
-
1745
- // Create and return a `Sammy.RenderContext` calling `render()` on it.
1746
- // Loads the template and interpolate the data, however does not actual
1747
- // place it in the DOM.
1748
- //
1749
- // ### Example
1750
- //
1751
- // // mytemplate.mustache <div class="name">{{name}}</div>
1752
- // render('mytemplate.mustache', {name: 'quirkey'});
1753
- // // sets the `content` to <div class="name">quirkey</div>
1754
- // render('mytemplate.mustache', {name: 'quirkey'})
1755
- // .appendTo('ul');
1756
- // // appends the rendered content to $('ul')
1757
- //
1758
- render: function(location, data, callback) {
1759
- return new Sammy.RenderContext(this).render(location, data, callback);
1760
- },
1761
-
1762
- // Create and return a `Sammy.RenderContext` calling `renderEach()` on it.
1763
- // Loads the template and interpolates the data for each item,
1764
- // however does not actual place it in the DOM.
1765
- //
1766
- // ### Example
1767
- //
1768
- // // mytemplate.mustache <div class="name">{{name}}</div>
1769
- // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}])
1770
- // // sets the `content` to <div class="name">quirkey</div><div class="name">endor</div>
1771
- // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}]).appendTo('ul');
1772
- // // appends the rendered content to $('ul')
1773
- //
1774
- renderEach: function(location, name, data, callback) {
1775
- return new Sammy.RenderContext(this).renderEach(location, name, data, callback);
1776
- },
1777
-
1778
- // create a new `Sammy.RenderContext` calling `load()` with `location` and
1779
- // `options`. Called without interpolation or placement, this allows for
1780
- // preloading/caching the templates.
1781
- load: function(location, options, callback) {
1782
- return new Sammy.RenderContext(this).load(location, options, callback);
1783
- },
1784
-
1785
- // `render()` the the `location` with `data` and then `swap()` the
1786
- // app's `$element` with the rendered content.
1787
- partial: function(location, data) {
1788
- return new Sammy.RenderContext(this).partial(location, data);
1789
- },
1790
-
1791
- // create a new `Sammy.RenderContext` calling `send()` with an arbitrary
1792
- // function
1793
- send: function() {
1794
- var rctx = new Sammy.RenderContext(this);
1795
- return rctx.send.apply(rctx, arguments);
1796
- },
1797
-
1798
- // Changes the location of the current window. If `to` begins with
1799
- // '#' it only changes the document's hash. If passed more than 1 argument
1800
- // redirect will join them together with forward slashes.
1801
- //
1802
- // ### Example
1803
- //
1804
- // redirect('#/other/route');
1805
- // // equivilent to
1806
- // redirect('#', 'other', 'route');
1807
- //
1808
- redirect: function() {
1809
- var to, args = _makeArray(arguments),
1810
- current_location = this.app.getLocation();
1811
- if (args.length > 1) {
1812
- args.unshift('/');
1813
- to = this.join.apply(this, args);
1814
- } else {
1815
- to = args[0];
1816
- }
1817
- this.trigger('redirect', {to: to});
1818
- this.app.last_location = [this.verb, this.path];
1819
- this.app.setLocation(to);
1820
- if (current_location == to) {
1821
- this.app.trigger('location-changed');
1822
- }
1823
- },
1824
-
1825
- // Triggers events on `app` within the current context.
1826
- trigger: function(name, data) {
1827
- if (typeof data == 'undefined') { data = {}; }
1828
- if (!data.context) { data.context = this; }
1829
- return this.app.trigger(name, data);
1830
- },
1831
-
1832
- // A shortcut to app's `eventNamespace()`
1833
- eventNamespace: function() {
1834
- return this.app.eventNamespace();
1835
- },
1836
-
1837
- // A shortcut to app's `swap()`
1838
- swap: function(contents) {
1839
- return this.app.swap(contents);
1840
- },
1841
-
1842
- // Raises a possible `notFound()` error for the current path.
1843
- notFound: function() {
1844
- return this.app.notFound(this.verb, this.path);
1845
- },
1846
-
1847
- // Default JSON parsing uses jQuery's `parseJSON()`. Include `Sammy.JSON`
1848
- // plugin for the more conformant "crockford special".
1849
- json: function(string) {
1850
- return $.parseJSON(string);
1851
- },
1852
-
1853
- // //=> Sammy.EventContext: get #/ {}
1854
- toString: function() {
1855
- return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
1856
- }
1857
-
1858
- });
1859
-
1860
- // An alias to Sammy
1861
- $.sammy = window.Sammy = Sammy;
1862
-
1863
- })(jQuery, window);
1
+ // name: sammy
2
+ // version: 0.6.2
3
+ /*
4
+
5
+ Copyright (c) 2008 Aaron Quint, Quirkey NYC, LLC
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.
24
+
25
+ */
26
+
27
+ (function($, window) {
28
+
29
+ var Sammy,
30
+ PATH_REPLACER = "([^\/]+)",
31
+ PATH_NAME_MATCHER = /:([\w\d]+)/g,
32
+ QUERY_STRING_MATCHER = /\?([^#]*)$/,
33
+ // mainly for making `arguments` an Array
34
+ _makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); },
35
+ // borrowed from jQuery
36
+ _isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; },
37
+ _isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; },
38
+ _decode = decodeURIComponent,
39
+ _encode = encodeURIComponent,
40
+ _escapeHTML = function(s) {
41
+ return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
42
+ },
43
+ _routeWrapper = function(verb) {
44
+ return function(path, callback) { return this.route.apply(this, [verb, path, callback]); };
45
+ },
46
+ _template_cache = {},
47
+ loggers = [];
48
+
49
+
50
+ // `Sammy` (also aliased as $.sammy) is not only the namespace for a
51
+ // number of prototypes, it's also a top level method that allows for easy
52
+ // creation/management of `Sammy.Application` instances. There are a
53
+ // number of different forms for `Sammy()` but each returns an instance
54
+ // of `Sammy.Application`. When a new instance is created using
55
+ // `Sammy` it is added to an Object called `Sammy.apps`. This
56
+ // provides for an easy way to get at existing Sammy applications. Only one
57
+ // instance is allowed per `element_selector` so when calling
58
+ // `Sammy('selector')` multiple times, the first time will create
59
+ // the application and the following times will extend the application
60
+ // already added to that selector.
61
+ //
62
+ // ### Example
63
+ //
64
+ // // returns the app at #main or a new app
65
+ // Sammy('#main')
66
+ //
67
+ // // equivilent to "new Sammy.Application", except appends to apps
68
+ // Sammy();
69
+ // Sammy(function() { ... });
70
+ //
71
+ // // extends the app at '#main' with function.
72
+ // Sammy('#main', function() { ... });
73
+ //
74
+ Sammy = function() {
75
+ var args = _makeArray(arguments),
76
+ app, selector;
77
+ Sammy.apps = Sammy.apps || {};
78
+ if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
79
+ return Sammy.apply(Sammy, ['body'].concat(args));
80
+ } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
81
+ app = Sammy.apps[selector] || new Sammy.Application();
82
+ app.element_selector = selector;
83
+ if (args.length > 0) {
84
+ $.each(args, function(i, plugin) {
85
+ app.use(plugin);
86
+ });
87
+ }
88
+ // if the selector changes make sure the refrence in Sammy.apps changes
89
+ if (app.element_selector != selector) {
90
+ delete Sammy.apps[selector];
91
+ }
92
+ Sammy.apps[app.element_selector] = app;
93
+ return app;
94
+ }
95
+ };
96
+
97
+ Sammy.VERSION = '0.6.2';
98
+
99
+ // Add to the global logger pool. Takes a function that accepts an
100
+ // unknown number of arguments and should print them or send them somewhere
101
+ // The first argument is always a timestamp.
102
+ Sammy.addLogger = function(logger) {
103
+ loggers.push(logger);
104
+ };
105
+
106
+ // Sends a log message to each logger listed in the global
107
+ // loggers pool. Can take any number of arguments.
108
+ // Also prefixes the arguments with a timestamp.
109
+ Sammy.log = function() {
110
+ var args = _makeArray(arguments);
111
+ args.unshift("[" + Date() + "]");
112
+ $.each(loggers, function(i, logger) {
113
+ logger.apply(Sammy, args);
114
+ });
115
+ };
116
+
117
+ if (typeof window.console != 'undefined') {
118
+ if (_isFunction(window.console.log.apply)) {
119
+ Sammy.addLogger(function() {
120
+ window.console.log.apply(window.console, arguments);
121
+ });
122
+ } else {
123
+ Sammy.addLogger(function() {
124
+ window.console.log(arguments);
125
+ });
126
+ }
127
+ } else if (typeof console != 'undefined') {
128
+ Sammy.addLogger(function() {
129
+ console.log.apply(console, arguments);
130
+ });
131
+ }
132
+
133
+ $.extend(Sammy, {
134
+ makeArray: _makeArray,
135
+ isFunction: _isFunction,
136
+ isArray: _isArray
137
+ })
138
+
139
+ // Sammy.Object is the base for all other Sammy classes. It provides some useful
140
+ // functionality, including cloning, iterating, etc.
141
+ Sammy.Object = function(obj) { // constructor
142
+ return $.extend(this, obj || {});
143
+ };
144
+
145
+ $.extend(Sammy.Object.prototype, {
146
+
147
+ // Escape HTML in string, use in templates to prevent script injection.
148
+ // Also aliased as `h()`
149
+ escapeHTML: _escapeHTML,
150
+ h: _escapeHTML,
151
+
152
+ // Returns a copy of the object with Functions removed.
153
+ toHash: function() {
154
+ var json = {};
155
+ $.each(this, function(k,v) {
156
+ if (!_isFunction(v)) {
157
+ json[k] = v;
158
+ }
159
+ });
160
+ return json;
161
+ },
162
+
163
+ // Renders a simple HTML version of this Objects attributes.
164
+ // Does not render functions.
165
+ // For example. Given this Sammy.Object:
166
+ //
167
+ // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
168
+ // s.toHTML() //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
169
+ //
170
+ toHTML: function() {
171
+ var display = "";
172
+ $.each(this, function(k, v) {
173
+ if (!_isFunction(v)) {
174
+ display += "<strong>" + k + "</strong> " + v + "<br />";
175
+ }
176
+ });
177
+ return display;
178
+ },
179
+
180
+ // Returns an array of keys for this object. If `attributes_only`
181
+ // is true will not return keys that map to a `function()`
182
+ keys: function(attributes_only) {
183
+ var keys = [];
184
+ for (var property in this) {
185
+ if (!_isFunction(this[property]) || !attributes_only) {
186
+ keys.push(property);
187
+ }
188
+ }
189
+ return keys;
190
+ },
191
+
192
+ // Checks if the object has a value at `key` and that the value is not empty
193
+ has: function(key) {
194
+ return this[key] && $.trim(this[key].toString()) != '';
195
+ },
196
+
197
+ // convenience method to join as many arguments as you want
198
+ // by the first argument - useful for making paths
199
+ join: function() {
200
+ var args = _makeArray(arguments);
201
+ var delimiter = args.shift();
202
+ return args.join(delimiter);
203
+ },
204
+
205
+ // Shortcut to Sammy.log
206
+ log: function() {
207
+ Sammy.log.apply(Sammy, arguments);
208
+ },
209
+
210
+ // Returns a string representation of this object.
211
+ // if `include_functions` is true, it will also toString() the
212
+ // methods of this object. By default only prints the attributes.
213
+ toString: function(include_functions) {
214
+ var s = [];
215
+ $.each(this, function(k, v) {
216
+ if (!_isFunction(v) || include_functions) {
217
+ s.push('"' + k + '": ' + v.toString());
218
+ }
219
+ });
220
+ return "Sammy.Object: {" + s.join(',') + "}";
221
+ }
222
+ });
223
+
224
+ // The HashLocationProxy is the default location proxy for all Sammy applications.
225
+ // A location proxy is a prototype that conforms to a simple interface. The purpose
226
+ // of a location proxy is to notify the Sammy.Application its bound to when the location
227
+ // or 'external state' changes. The HashLocationProxy considers the state to be
228
+ // changed when the 'hash' (window.location.hash / '#') changes. It does this in two
229
+ // different ways depending on what browser you are using. The newest browsers
230
+ // (IE, Safari > 4, FF >= 3.6) support a 'onhashchange' DOM event, thats fired whenever
231
+ // the location.hash changes. In this situation the HashLocationProxy just binds
232
+ // to this event and delegates it to the application. In the case of older browsers
233
+ // a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier,
234
+ // the HashLocationProxy allows the poller to be a global object, eliminating the
235
+ // need for multiple pollers even when thier are multiple apps on the page.
236
+ Sammy.HashLocationProxy = function(app, run_interval_every) {
237
+ this.app = app;
238
+ // set is native to false and start the poller immediately
239
+ this.is_native = false;
240
+ this._startPolling(run_interval_every);
241
+ };
242
+
243
+ Sammy.HashLocationProxy.prototype = {
244
+
245
+ // bind the proxy events to the current app.
246
+ bind: function() {
247
+ var proxy = this, app = this.app;
248
+ $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
249
+ // if we receive a native hash change event, set the proxy accordingly
250
+ // and stop polling
251
+ if (proxy.is_native === false && !non_native) {
252
+ Sammy.log('native hash change exists, using');
253
+ proxy.is_native = true;
254
+ window.clearInterval(Sammy.HashLocationProxy._interval);
255
+ }
256
+ app.trigger('location-changed');
257
+ });
258
+ if (!Sammy.HashLocationProxy._bindings) {
259
+ Sammy.HashLocationProxy._bindings = 0;
260
+ }
261
+ Sammy.HashLocationProxy._bindings++;
262
+ },
263
+
264
+ // unbind the proxy events from the current app
265
+ unbind: function() {
266
+ $(window).unbind('hashchange.' + this.app.eventNamespace());
267
+ Sammy.HashLocationProxy._bindings--;
268
+ if (Sammy.HashLocationProxy._bindings <= 0) {
269
+ window.clearInterval(Sammy.HashLocationProxy._interval);
270
+ }
271
+ },
272
+
273
+ // get the current location from the hash.
274
+ getLocation: function() {
275
+ // Bypass the `window.location.hash` attribute. If a question mark
276
+ // appears in the hash IE6 will strip it and all of the following
277
+ // characters from `window.location.hash`.
278
+ var matches = window.location.toString().match(/^[^#]*(#.+)$/);
279
+ return matches ? matches[1] : '';
280
+ },
281
+
282
+ // set the current location to `new_location`
283
+ setLocation: function(new_location) {
284
+ return (window.location = new_location);
285
+ },
286
+
287
+ _startPolling: function(every) {
288
+ // set up interval
289
+ var proxy = this;
290
+ if (!Sammy.HashLocationProxy._interval) {
291
+ if (!every) { every = 10; }
292
+ var hashCheck = function() {
293
+ var current_location = proxy.getLocation();
294
+ if (!Sammy.HashLocationProxy._last_location ||
295
+ current_location != Sammy.HashLocationProxy._last_location) {
296
+ window.setTimeout(function() {
297
+ $(window).trigger('hashchange', [true]);
298
+ }, 13);
299
+ }
300
+ Sammy.HashLocationProxy._last_location = current_location;
301
+ };
302
+ hashCheck();
303
+ Sammy.HashLocationProxy._interval = window.setInterval(hashCheck, every);
304
+ }
305
+ }
306
+ };
307
+
308
+
309
+ // Sammy.Application is the Base prototype for defining 'applications'.
310
+ // An 'application' is a collection of 'routes' and bound events that is
311
+ // attached to an element when `run()` is called.
312
+ // The only argument an 'app_function' is evaluated within the context of the application.
313
+ Sammy.Application = function(app_function) {
314
+ var app = this;
315
+ this.routes = {};
316
+ this.listeners = new Sammy.Object({});
317
+ this.arounds = [];
318
+ this.befores = [];
319
+ // generate a unique namespace
320
+ this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
321
+ this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
322
+ this.context_prototype.prototype = new Sammy.EventContext();
323
+
324
+ if (_isFunction(app_function)) {
325
+ app_function.apply(this, [this]);
326
+ }
327
+ // set the location proxy if not defined to the default (HashLocationProxy)
328
+ if (!this._location_proxy) {
329
+ this.setLocationProxy(new Sammy.HashLocationProxy(this, this.run_interval_every));
330
+ }
331
+ if (this.debug) {
332
+ this.bindToAllEvents(function(e, data) {
333
+ app.log(app.toString(), e.cleaned_type, data || {});
334
+ });
335
+ }
336
+ };
337
+
338
+ Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
339
+
340
+ // the four route verbs
341
+ ROUTE_VERBS: ['get','post','put','delete'],
342
+
343
+ // An array of the default events triggered by the
344
+ // application during its lifecycle
345
+ APP_EVENTS: ['run',
346
+ 'unload',
347
+ 'lookup-route',
348
+ 'run-route',
349
+ 'route-found',
350
+ 'event-context-before',
351
+ 'event-context-after',
352
+ 'changed',
353
+ 'error',
354
+ 'check-form-submission',
355
+ 'redirect',
356
+ 'location-changed'],
357
+
358
+ _last_route: null,
359
+ _location_proxy: null,
360
+ _running: false,
361
+
362
+ // Defines what element the application is bound to. Provide a selector
363
+ // (parseable by `jQuery()`) and this will be used by `$element()`
364
+ element_selector: 'body',
365
+
366
+ // When set to true, logs all of the default events using `log()`
367
+ debug: false,
368
+
369
+ // When set to true, and the error() handler is not overriden, will actually
370
+ // raise JS errors in routes (500) and when routes can't be found (404)
371
+ raise_errors: false,
372
+
373
+ // The time in milliseconds that the URL is queried for changes
374
+ run_interval_every: 50,
375
+
376
+ // The default template engine to use when using `partial()` in an
377
+ // `EventContext`. `template_engine` can either be a string that
378
+ // corresponds to the name of a method/helper on EventContext or it can be a function
379
+ // that takes two arguments, the content of the unrendered partial and an optional
380
+ // JS object that contains interpolation data. Template engine is only called/refered
381
+ // to if the extension of the partial is null or unknown. See `partial()`
382
+ // for more information
383
+ template_engine: null,
384
+
385
+ // //=> Sammy.Application: body
386
+ toString: function() {
387
+ return 'Sammy.Application:' + this.element_selector;
388
+ },
389
+
390
+ // returns a jQuery object of the Applications bound element.
391
+ $element: function(selector) {
392
+ return selector ? $(this.element_selector).find(selector) : $(this.element_selector);
393
+ },
394
+
395
+ // `use()` is the entry point for including Sammy plugins.
396
+ // The first argument to use should be a function() that is evaluated
397
+ // in the context of the current application, just like the `app_function`
398
+ // argument to the `Sammy.Application` constructor.
399
+ //
400
+ // Any additional arguments are passed to the app function sequentially.
401
+ //
402
+ // For much more detail about plugins, check out:
403
+ // http://code.quirkey.com/sammy/doc/plugins.html
404
+ //
405
+ // ### Example
406
+ //
407
+ // var MyPlugin = function(app, prepend) {
408
+ //
409
+ // this.helpers({
410
+ // myhelper: function(text) {
411
+ // alert(prepend + " " + text);
412
+ // }
413
+ // });
414
+ //
415
+ // };
416
+ //
417
+ // var app = $.sammy(function() {
418
+ //
419
+ // this.use(MyPlugin, 'This is my plugin');
420
+ //
421
+ // this.get('#/', function() {
422
+ // this.myhelper('and dont you forget it!');
423
+ // //=> Alerts: This is my plugin and dont you forget it!
424
+ // });
425
+ //
426
+ // });
427
+ //
428
+ // If plugin is passed as a string it assumes your are trying to load
429
+ // Sammy."Plugin". This is the prefered way of loading core Sammy plugins
430
+ // as it allows for better error-messaging.
431
+ //
432
+ // ### Example
433
+ //
434
+ // $.sammy(function() {
435
+ // this.use('Mustache'); //=> Sammy.Mustache
436
+ // this.use('Storage'); //=> Sammy.Storage
437
+ // });
438
+ //
439
+ use: function() {
440
+ // flatten the arguments
441
+ var args = _makeArray(arguments),
442
+ plugin = args.shift(),
443
+ plugin_name = plugin || '';
444
+ try {
445
+ args.unshift(this);
446
+ if (typeof plugin == 'string') {
447
+ plugin_name = 'Sammy.' + plugin;
448
+ plugin = Sammy[plugin];
449
+ }
450
+ plugin.apply(this, args);
451
+ } catch(e) {
452
+ if (typeof plugin === 'undefined') {
453
+ this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
454
+ } else if (!_isFunction(plugin)) {
455
+ this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
456
+ } else {
457
+ this.error("Plugin Error", e);
458
+ }
459
+ }
460
+ return this;
461
+ },
462
+
463
+ // Sets the location proxy for the current app. By default this is set to
464
+ // a new `Sammy.HashLocationProxy` on initialization. However, you can set
465
+ // the location_proxy inside you're app function to give your app a custom
466
+ // location mechanism. See `Sammy.HashLocationProxy` and `Sammy.DataLocationProxy`
467
+ // for examples.
468
+ //
469
+ // `setLocationProxy()` takes an initialized location proxy.
470
+ //
471
+ // ### Example
472
+ //
473
+ // // to bind to data instead of the default hash;
474
+ // var app = $.sammy(function() {
475
+ // this.setLocationProxy(new Sammy.DataLocationProxy(this));
476
+ // });
477
+ //
478
+ setLocationProxy: function(new_proxy) {
479
+ var original_proxy = this._location_proxy;
480
+ this._location_proxy = new_proxy;
481
+ if (this.isRunning()) {
482
+ if (original_proxy) {
483
+ // if there is already a location proxy, unbind it.
484
+ original_proxy.unbind();
485
+ }
486
+ this._location_proxy.bind();
487
+ }
488
+ },
489
+
490
+ // `route()` is the main method for defining routes within an application.
491
+ // For great detail on routes, check out: http://code.quirkey.com/sammy/doc/routes.html
492
+ //
493
+ // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
494
+ //
495
+ // ### Arguments
496
+ //
497
+ // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
498
+ // of the ROUTE_VERBS. If only two arguments are passed,
499
+ // the first argument is the path, the second is the callback and the verb
500
+ // is assumed to be 'any'.
501
+ // * `path` A Regexp or a String representing the path to match to invoke this verb.
502
+ // * `callback` A Function that is called/evaluated whent the route is run see: `runRoute()`.
503
+ // It is also possible to pass a string as the callback, which is looked up as the name
504
+ // of a method on the application.
505
+ //
506
+ route: function(verb, path, callback) {
507
+ var app = this, param_names = [], add_route, path_match;
508
+
509
+ // if the method signature is just (path, callback)
510
+ // assume the verb is 'any'
511
+ if (!callback && _isFunction(path)) {
512
+ path = verb;
513
+ callback = path;
514
+ verb = 'any';
515
+ }
516
+
517
+ verb = verb.toLowerCase(); // ensure verb is lower case
518
+
519
+ // if path is a string turn it into a regex
520
+ if (path.constructor == String) {
521
+
522
+ // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
523
+ // which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params
524
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
525
+ PATH_NAME_MATCHER.lastIndex = 0;
526
+
527
+ // find the names
528
+ while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
529
+ param_names.push(path_match[1]);
530
+ }
531
+ // replace with the path replacement
532
+ path = new RegExp("^" + path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
533
+ }
534
+ // lookup callback
535
+ if (typeof callback == 'string') {
536
+ callback = app[callback];
537
+ }
538
+
539
+ add_route = function(with_verb) {
540
+ var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
541
+ // add route to routes array
542
+ app.routes[with_verb] = app.routes[with_verb] || [];
543
+ // place routes in order of definition
544
+ app.routes[with_verb].push(r);
545
+ };
546
+
547
+ if (verb === 'any') {
548
+ $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
549
+ } else {
550
+ add_route(verb);
551
+ }
552
+
553
+ // return the app
554
+ return this;
555
+ },
556
+
557
+ // Alias for route('get', ...)
558
+ get: _routeWrapper('get'),
559
+
560
+ // Alias for route('post', ...)
561
+ post: _routeWrapper('post'),
562
+
563
+ // Alias for route('put', ...)
564
+ put: _routeWrapper('put'),
565
+
566
+ // Alias for route('delete', ...)
567
+ del: _routeWrapper('delete'),
568
+
569
+ // Alias for route('any', ...)
570
+ any: _routeWrapper('any'),
571
+
572
+ // `mapRoutes` takes an array of arrays, each array being passed to route()
573
+ // as arguments, this allows for mass definition of routes. Another benefit is
574
+ // this makes it possible/easier to load routes via remote JSON.
575
+ //
576
+ // ### Example
577
+ //
578
+ // var app = $.sammy(function() {
579
+ //
580
+ // this.mapRoutes([
581
+ // ['get', '#/', function() { this.log('index'); }],
582
+ // // strings in callbacks are looked up as methods on the app
583
+ // ['post', '#/create', 'addUser'],
584
+ // // No verb assumes 'any' as the verb
585
+ // [/dowhatever/, function() { this.log(this.verb, this.path)}];
586
+ // ]);
587
+ // })
588
+ //
589
+ mapRoutes: function(route_array) {
590
+ var app = this;
591
+ $.each(route_array, function(i, route_args) {
592
+ app.route.apply(app, route_args);
593
+ });
594
+ return this;
595
+ },
596
+
597
+ // A unique event namespace defined per application.
598
+ // All events bound with `bind()` are automatically bound within this space.
599
+ eventNamespace: function() {
600
+ return ['sammy-app', this.namespace].join('-');
601
+ },
602
+
603
+ // Works just like `jQuery.fn.bind()` with a couple noteable differences.
604
+ //
605
+ // * It binds all events to the application element
606
+ // * All events are bound within the `eventNamespace()`
607
+ // * Events are not actually bound until the application is started with `run()`
608
+ // * callbacks are evaluated within the context of a Sammy.EventContext
609
+ //
610
+ // See http://code.quirkey.com/sammy/docs/events.html for more info.
611
+ //
612
+ bind: function(name, data, callback) {
613
+ var app = this;
614
+ // build the callback
615
+ // if the arity is 2, callback is the second argument
616
+ if (typeof callback == 'undefined') { callback = data; }
617
+ var listener_callback = function() {
618
+ // pull off the context from the arguments to the callback
619
+ var e, context, data;
620
+ e = arguments[0];
621
+ data = arguments[1];
622
+ if (data && data.context) {
623
+ context = data.context;
624
+ delete data.context;
625
+ } else {
626
+ context = new app.context_prototype(app, 'bind', e.type, data, e.target);
627
+ }
628
+ e.cleaned_type = e.type.replace(app.eventNamespace(), '');
629
+ callback.apply(context, [e, data]);
630
+ };
631
+
632
+ // it could be that the app element doesnt exist yet
633
+ // so attach to the listeners array and then run()
634
+ // will actually bind the event.
635
+ if (!this.listeners[name]) { this.listeners[name] = []; }
636
+ this.listeners[name].push(listener_callback);
637
+ if (this.isRunning()) {
638
+ // if the app is running
639
+ // *actually* bind the event to the app element
640
+ this._listen(name, listener_callback);
641
+ }
642
+ return this;
643
+ },
644
+
645
+ // Triggers custom events defined with `bind()`
646
+ //
647
+ // ### Arguments
648
+ //
649
+ // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
650
+ // * `data` An optional Object that can be passed to the bound callback.
651
+ // * `context` An optional context/Object in which to execute the bound callback.
652
+ // If no context is supplied a the context is a new `Sammy.EventContext`
653
+ //
654
+ trigger: function(name, data) {
655
+ this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
656
+ return this;
657
+ },
658
+
659
+ // Reruns the current route
660
+ refresh: function() {
661
+ this.last_location = null;
662
+ this.trigger('location-changed');
663
+ return this;
664
+ },
665
+
666
+ // Takes a single callback that is pushed on to a stack.
667
+ // Before any route is run, the callbacks are evaluated in order within
668
+ // the current `Sammy.EventContext`
669
+ //
670
+ // If any of the callbacks explicitly return false, execution of any
671
+ // further callbacks and the route itself is halted.
672
+ //
673
+ // You can also provide a set of options that will define when to run this
674
+ // before based on the route it proceeds.
675
+ //
676
+ // ### Example
677
+ //
678
+ // var app = $.sammy(function() {
679
+ //
680
+ // // will run at #/route but not at #/
681
+ // this.before('#/route', function() {
682
+ // //...
683
+ // });
684
+ //
685
+ // // will run at #/ but not at #/route
686
+ // this.before({except: {path: '#/route'}}, function() {
687
+ // this.log('not before #/route');
688
+ // });
689
+ //
690
+ // this.get('#/', function() {});
691
+ //
692
+ // this.get('#/route', function() {});
693
+ //
694
+ // });
695
+ //
696
+ // See `contextMatchesOptions()` for a full list of supported options
697
+ //
698
+ before: function(options, callback) {
699
+ if (_isFunction(options)) {
700
+ callback = options;
701
+ options = {};
702
+ }
703
+ this.befores.push([options, callback]);
704
+ return this;
705
+ },
706
+
707
+ // A shortcut for binding a callback to be run after a route is executed.
708
+ // After callbacks have no guarunteed order.
709
+ after: function(callback) {
710
+ return this.bind('event-context-after', callback);
711
+ },
712
+
713
+
714
+ // Adds an around filter to the application. around filters are functions
715
+ // that take a single argument `callback` which is the entire route
716
+ // execution path wrapped up in a closure. This means you can decide whether
717
+ // or not to proceed with execution by not invoking `callback` or,
718
+ // more usefuly wrapping callback inside the result of an asynchronous execution.
719
+ //
720
+ // ### Example
721
+ //
722
+ // The most common use case for around() is calling a _possibly_ async function
723
+ // and executing the route within the functions callback:
724
+ //
725
+ // var app = $.sammy(function() {
726
+ //
727
+ // var current_user = false;
728
+ //
729
+ // function checkLoggedIn(callback) {
730
+ // // /session returns a JSON representation of the logged in user
731
+ // // or an empty object
732
+ // if (!current_user) {
733
+ // $.getJSON('/session', function(json) {
734
+ // if (json.login) {
735
+ // // show the user as logged in
736
+ // current_user = json;
737
+ // // execute the route path
738
+ // callback();
739
+ // } else {
740
+ // // show the user as not logged in
741
+ // current_user = false;
742
+ // // the context of aroundFilters is an EventContext
743
+ // this.redirect('#/login');
744
+ // }
745
+ // });
746
+ // } else {
747
+ // // execute the route path
748
+ // callback();
749
+ // }
750
+ // };
751
+ //
752
+ // this.around(checkLoggedIn);
753
+ //
754
+ // });
755
+ //
756
+ around: function(callback) {
757
+ this.arounds.push(callback);
758
+ return this;
759
+ },
760
+
761
+ // Returns `true` if the current application is running.
762
+ isRunning: function() {
763
+ return this._running;
764
+ },
765
+
766
+ // Helpers extends the EventContext prototype specific to this app.
767
+ // This allows you to define app specific helper functions that can be used
768
+ // whenever you're inside of an event context (templates, routes, bind).
769
+ //
770
+ // ### Example
771
+ //
772
+ // var app = $.sammy(function() {
773
+ //
774
+ // helpers({
775
+ // upcase: function(text) {
776
+ // return text.toString().toUpperCase();
777
+ // }
778
+ // });
779
+ //
780
+ // get('#/', function() { with(this) {
781
+ // // inside of this context I can use the helpers
782
+ // $('#main').html(upcase($('#main').text());
783
+ // }});
784
+ //
785
+ // });
786
+ //
787
+ //
788
+ // ### Arguments
789
+ //
790
+ // * `extensions` An object collection of functions to extend the context.
791
+ //
792
+ helpers: function(extensions) {
793
+ $.extend(this.context_prototype.prototype, extensions);
794
+ return this;
795
+ },
796
+
797
+ // Helper extends the event context just like `helpers()` but does it
798
+ // a single method at a time. This is especially useful for dynamically named
799
+ // helpers
800
+ //
801
+ // ### Example
802
+ //
803
+ // // Trivial example that adds 3 helper methods to the context dynamically
804
+ // var app = $.sammy(function(app) {
805
+ //
806
+ // $.each([1,2,3], function(i, num) {
807
+ // app.helper('helper' + num, function() {
808
+ // this.log("I'm helper number " + num);
809
+ // });
810
+ // });
811
+ //
812
+ // this.get('#/', function() {
813
+ // this.helper2(); //=> I'm helper number 2
814
+ // });
815
+ // });
816
+ //
817
+ // ### Arguments
818
+ //
819
+ // * `name` The name of the method
820
+ // * `method` The function to be added to the prototype at `name`
821
+ //
822
+ helper: function(name, method) {
823
+ this.context_prototype.prototype[name] = method;
824
+ return this;
825
+ },
826
+
827
+ // Actually starts the application's lifecycle. `run()` should be invoked
828
+ // within a document.ready block to ensure the DOM exists before binding events, etc.
829
+ //
830
+ // ### Example
831
+ //
832
+ // var app = $.sammy(function() { ... }); // your application
833
+ // $(function() { // document.ready
834
+ // app.run();
835
+ // });
836
+ //
837
+ // ### Arguments
838
+ //
839
+ // * `start_url` Optionally, a String can be passed which the App will redirect to
840
+ // after the events/routes have been bound.
841
+ run: function(start_url) {
842
+ if (this.isRunning()) { return false; }
843
+ var app = this;
844
+
845
+ // actually bind all the listeners
846
+ $.each(this.listeners.toHash(), function(name, callbacks) {
847
+ $.each(callbacks, function(i, listener_callback) {
848
+ app._listen(name, listener_callback);
849
+ });
850
+ });
851
+
852
+ this.trigger('run', {start_url: start_url});
853
+ this._running = true;
854
+ // set last location
855
+ this.last_location = null;
856
+ if (this.getLocation() == '' && typeof start_url != 'undefined') {
857
+ this.setLocation(start_url);
858
+ }
859
+ // check url
860
+ this._checkLocation();
861
+ this._location_proxy.bind();
862
+ this.bind('location-changed', function() {
863
+ app._checkLocation();
864
+ });
865
+
866
+ // bind to submit to capture post/put/delete routes
867
+ /*
868
+ this.bind('submit', function(e) {
869
+ var returned = app._checkFormSubmission($(e.target).closest('form'));
870
+ return (returned === false) ? e.preventDefault() : false;
871
+ });
872
+ */
873
+
874
+ // bind unload to body unload
875
+ $(window).bind('beforeunload', function() {
876
+ app.unload();
877
+ });
878
+
879
+ // trigger html changed
880
+ return this.trigger('changed');
881
+ },
882
+
883
+ // The opposite of `run()`, un-binds all event listeners and intervals
884
+ // `run()` Automaticaly binds a `onunload` event to run this when
885
+ // the document is closed.
886
+ unload: function() {
887
+ if (!this.isRunning()) { return false; }
888
+ var app = this;
889
+ this.trigger('unload');
890
+ // clear interval
891
+ this._location_proxy.unbind();
892
+ // unbind form submits
893
+ this.$element().unbind('submit').removeClass(app.eventNamespace());
894
+ // unbind all events
895
+ $.each(this.listeners.toHash() , function(name, listeners) {
896
+ $.each(listeners, function(i, listener_callback) {
897
+ app._unlisten(name, listener_callback);
898
+ });
899
+ });
900
+ this._running = false;
901
+ return this;
902
+ },
903
+
904
+ // Will bind a single callback function to every event that is already
905
+ // being listened to in the app. This includes all the `APP_EVENTS`
906
+ // as well as any custom events defined with `bind()`.
907
+ //
908
+ // Used internally for debug logging.
909
+ bindToAllEvents: function(callback) {
910
+ var app = this;
911
+ // bind to the APP_EVENTS first
912
+ $.each(this.APP_EVENTS, function(i, e) {
913
+ app.bind(e, callback);
914
+ });
915
+ // next, bind to listener names (only if they dont exist in APP_EVENTS)
916
+ $.each(this.listeners.keys(true), function(i, name) {
917
+ if (app.APP_EVENTS.indexOf(name) == -1) {
918
+ app.bind(name, callback);
919
+ }
920
+ });
921
+ return this;
922
+ },
923
+
924
+ // Returns a copy of the given path with any query string after the hash
925
+ // removed.
926
+ routablePath: function(path) {
927
+ return path.replace(QUERY_STRING_MATCHER, '');
928
+ },
929
+
930
+ // Given a verb and a String path, will return either a route object or false
931
+ // if a matching route can be found within the current defined set.
932
+ lookupRoute: function(verb, path) {
933
+ var app = this, routed = false;
934
+ this.trigger('lookup-route', {verb: verb, path: path});
935
+ if (typeof this.routes[verb] != 'undefined') {
936
+ $.each(this.routes[verb], function(i, route) {
937
+ if (app.routablePath(path).match(route.path)) {
938
+ routed = route;
939
+ return false;
940
+ }
941
+ });
942
+ }
943
+ return routed;
944
+ },
945
+
946
+ // First, invokes `lookupRoute()` and if a route is found, parses the
947
+ // possible URL params and then invokes the route's callback within a new
948
+ // `Sammy.EventContext`. If the route can not be found, it calls
949
+ // `notFound()`. If `raise_errors` is set to `true` and
950
+ // the `error()` has not been overriden, it will throw an actual JS
951
+ // error.
952
+ //
953
+ // You probably will never have to call this directly.
954
+ //
955
+ // ### Arguments
956
+ //
957
+ // * `verb` A String for the verb.
958
+ // * `path` A String path to lookup.
959
+ // * `params` An Object of Params pulled from the URI or passed directly.
960
+ //
961
+ // ### Returns
962
+ //
963
+ // Either returns the value returned by the route callback or raises a 404 Not Found error.
964
+ //
965
+ runRoute: function(verb, path, params, target) {
966
+ var app = this,
967
+ route = this.lookupRoute(verb, path),
968
+ context,
969
+ wrapped_route,
970
+ arounds,
971
+ around,
972
+ befores,
973
+ before,
974
+ callback_args,
975
+ path_params,
976
+ final_returned;
977
+
978
+ this.log('runRoute', [verb, path].join(' '));
979
+ this.trigger('run-route', {verb: verb, path: path, params: params});
980
+ if (typeof params == 'undefined') { params = {}; }
981
+
982
+ $.extend(params, this._parseQueryString(path));
983
+
984
+ if (route) {
985
+ this.trigger('route-found', {route: route});
986
+ // pull out the params from the path
987
+ if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
988
+ // first match is the full path
989
+ path_params.shift();
990
+ // for each of the matches
991
+ $.each(path_params, function(i, param) {
992
+ // if theres a matching param name
993
+ if (route.param_names[i]) {
994
+ // set the name to the match
995
+ params[route.param_names[i]] = _decode(param);
996
+ } else {
997
+ // initialize 'splat'
998
+ if (!params.splat) { params.splat = []; }
999
+ params.splat.push(_decode(param));
1000
+ }
1001
+ });
1002
+ }
1003
+
1004
+ // set event context
1005
+ context = new this.context_prototype(this, verb, path, params, target);
1006
+ // ensure arrays
1007
+ arounds = this.arounds.slice(0);
1008
+ befores = this.befores.slice(0);
1009
+ // set the callback args to the context + contents of the splat
1010
+ callback_args = [context].concat(params.splat);
1011
+ // wrap the route up with the before filters
1012
+ wrapped_route = function() {
1013
+ var returned;
1014
+ while (befores.length > 0) {
1015
+ before = befores.shift();
1016
+ // check the options
1017
+ if (app.contextMatchesOptions(context, before[0])) {
1018
+ returned = before[1].apply(context, [context]);
1019
+ if (returned === false) { return false; }
1020
+ }
1021
+ }
1022
+ app.last_route = route;
1023
+ context.trigger('event-context-before', {context: context});
1024
+ returned = route.callback.apply(context, callback_args);
1025
+ context.trigger('event-context-after', {context: context});
1026
+ return returned;
1027
+ };
1028
+ $.each(arounds.reverse(), function(i, around) {
1029
+ var last_wrapped_route = wrapped_route;
1030
+ wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
1031
+ });
1032
+ try {
1033
+ final_returned = wrapped_route();
1034
+ } catch(e) {
1035
+ this.error(['500 Error', verb, path].join(' '), e);
1036
+ }
1037
+ return final_returned;
1038
+ } else {
1039
+ return this.notFound(verb, path);
1040
+ }
1041
+ },
1042
+
1043
+ // Matches an object of options against an `EventContext` like object that
1044
+ // contains `path` and `verb` attributes. Internally Sammy uses this
1045
+ // for matching `before()` filters against specific options. You can set the
1046
+ // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
1047
+ // those that match the options.
1048
+ //
1049
+ // ### Example
1050
+ //
1051
+ // var app = $.sammy(),
1052
+ // context = {verb: 'get', path: '#/mypath'};
1053
+ //
1054
+ // // match against a path string
1055
+ // app.contextMatchesOptions(context, '#/mypath'); //=> true
1056
+ // app.contextMatchesOptions(context, '#/otherpath'); //=> false
1057
+ // // equivilent to
1058
+ // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
1059
+ // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
1060
+ // // match against a path regexp
1061
+ // app.contextMatchesOptions(context, /path/); //=> true
1062
+ // app.contextMatchesOptions(context, /^path/); //=> false
1063
+ // // match only a verb
1064
+ // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
1065
+ // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
1066
+ // // match all except a verb
1067
+ // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
1068
+ // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
1069
+ // // match all except a path
1070
+ // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
1071
+ // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
1072
+ //
1073
+ contextMatchesOptions: function(context, match_options, positive) {
1074
+ // empty options always match
1075
+ var options = match_options;
1076
+ if (typeof options === 'undefined' || options == {}) {
1077
+ return true;
1078
+ }
1079
+ if (typeof positive === 'undefined') {
1080
+ positive = true;
1081
+ }
1082
+ // normalize options
1083
+ if (typeof options === 'string' || _isFunction(options.test)) {
1084
+ options = {path: options};
1085
+ }
1086
+ if (options.only) {
1087
+ return this.contextMatchesOptions(context, options.only, true);
1088
+ } else if (options.except) {
1089
+ return this.contextMatchesOptions(context, options.except, false);
1090
+ }
1091
+ var path_matched = true, verb_matched = true;
1092
+ if (options.path) {
1093
+ // wierd regexp test
1094
+ if (_isFunction(options.path.test)) {
1095
+ path_matched = options.path.test(context.path);
1096
+ } else {
1097
+ path_matched = (options.path.toString() === context.path);
1098
+ }
1099
+ }
1100
+ if (options.verb) {
1101
+ verb_matched = options.verb === context.verb;
1102
+ }
1103
+ return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
1104
+ },
1105
+
1106
+
1107
+ // Delegates to the `location_proxy` to get the current location.
1108
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1109
+ getLocation: function() {
1110
+ return this._location_proxy.getLocation();
1111
+ },
1112
+
1113
+ // Delegates to the `location_proxy` to set the current location.
1114
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1115
+ //
1116
+ // ### Arguments
1117
+ //
1118
+ // * `new_location` A new location string (e.g. '#/')
1119
+ //
1120
+ setLocation: function(new_location) {
1121
+ return this._location_proxy.setLocation(new_location);
1122
+ },
1123
+
1124
+ // Swaps the content of `$element()` with `content`
1125
+ // You can override this method to provide an alternate swap behavior
1126
+ // for `EventContext.partial()`.
1127
+ //
1128
+ // ### Example
1129
+ //
1130
+ // var app = $.sammy(function() {
1131
+ //
1132
+ // // implements a 'fade out'/'fade in'
1133
+ // this.swap = function(content) {
1134
+ // this.$element().hide('slow').html(content).show('slow');
1135
+ // }
1136
+ //
1137
+ // get('#/', function() {
1138
+ // this.partial('index.html.erb') // will fade out and in
1139
+ // });
1140
+ //
1141
+ // });
1142
+ //
1143
+ swap: function(content) {
1144
+ return this.$element().html(content);
1145
+ },
1146
+
1147
+ // a simple global cache for templates. Uses the same semantics as
1148
+ // `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
1149
+ // a persistant storage that lasts beyond the current request.
1150
+ templateCache: function(key, value) {
1151
+ if (typeof value != 'undefined') {
1152
+ return _template_cache[key] = value;
1153
+ } else {
1154
+ return _template_cache[key];
1155
+ }
1156
+ },
1157
+
1158
+ // clear the templateCache
1159
+ clearTemplateCache: function() {
1160
+ return _template_cache = {};
1161
+ },
1162
+
1163
+ // This thows a '404 Not Found' error by invoking `error()`.
1164
+ // Override this method or `error()` to provide custom
1165
+ // 404 behavior (i.e redirecting to / or showing a warning)
1166
+ notFound: function(verb, path) {
1167
+ var ret = this.error(['404 Not Found', verb, path].join(' '));
1168
+ return (verb === 'get') ? ret : true;
1169
+ },
1170
+
1171
+ // The base error handler takes a string `message` and an `Error`
1172
+ // object. If `raise_errors` is set to `true` on the app level,
1173
+ // this will re-throw the error to the browser. Otherwise it will send the error
1174
+ // to `log()`. Override this method to provide custom error handling
1175
+ // e.g logging to a server side component or displaying some feedback to the
1176
+ // user.
1177
+ error: function(message, original_error) {
1178
+ if (!original_error) { original_error = new Error(); }
1179
+ original_error.message = [message, original_error.message].join(' ');
1180
+ this.trigger('error', {message: original_error.message, error: original_error});
1181
+ if (this.raise_errors) {
1182
+ throw(original_error);
1183
+ } else {
1184
+ this.log(original_error.message, original_error);
1185
+ }
1186
+ },
1187
+
1188
+ _checkLocation: function() {
1189
+ var location, returned;
1190
+ // get current location
1191
+ location = this.getLocation();
1192
+ // compare to see if hash has changed
1193
+ if (!this.last_location || this.last_location[0] != 'get' || this.last_location[1] != location) {
1194
+ // reset last location
1195
+ this.last_location = ['get', location];
1196
+ // lookup route for current hash
1197
+ returned = this.runRoute('get', location);
1198
+ }
1199
+ return returned;
1200
+ },
1201
+
1202
+ _getFormVerb: function(form) {
1203
+ var $form = $(form), verb, $_method;
1204
+ $_method = $form.find('input[name="_method"]');
1205
+ if ($_method.length > 0) { verb = $_method.val(); }
1206
+ if (!verb) { verb = $form[0].getAttribute('method'); }
1207
+ return $.trim(verb.toString().toLowerCase());
1208
+ },
1209
+
1210
+ _checkFormSubmission: function(form) {
1211
+ var $form, path, verb, params, returned;
1212
+ this.trigger('check-form-submission', {form: form});
1213
+ $form = $(form);
1214
+ path = $form.attr('action');
1215
+ verb = this._getFormVerb($form);
1216
+ if (!verb || verb == '') { verb = 'get'; }
1217
+ this.log('_checkFormSubmission', $form, path, verb);
1218
+ if (verb === 'get') {
1219
+ this.setLocation(path + '?' + this._serializeFormParams($form));
1220
+ returned = false;
1221
+ } else {
1222
+ params = $.extend({}, this._parseFormParams($form));
1223
+ returned = this.runRoute(verb, path, params, form.get(0));
1224
+ };
1225
+ return (typeof returned == 'undefined') ? false : returned;
1226
+ },
1227
+
1228
+ _serializeFormParams: function($form) {
1229
+ var queryString = "",
1230
+ fields = $form.serializeArray(),
1231
+ i;
1232
+ if (fields.length > 0) {
1233
+ queryString = this._encodeFormPair(fields[0].name, fields[0].value);
1234
+ for (i = 1; i < fields.length; i++) {
1235
+ queryString = queryString + "&" + this._encodeFormPair(fields[i].name, fields[i].value);
1236
+ }
1237
+ }
1238
+ return queryString;
1239
+ },
1240
+
1241
+ _encodeFormPair: function(name, value){
1242
+ return _encode(name) + "=" + _encode(value);
1243
+ },
1244
+
1245
+ _parseFormParams: function($form) {
1246
+ var params = {},
1247
+ form_fields = $form.serializeArray(),
1248
+ i;
1249
+ for (i = 0; i < form_fields.length; i++) {
1250
+ params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
1251
+ }
1252
+ return params;
1253
+ },
1254
+
1255
+ _parseQueryString: function(path) {
1256
+ var params = {}, parts, pairs, pair, i;
1257
+
1258
+ parts = path.match(QUERY_STRING_MATCHER);
1259
+ if (parts) {
1260
+ pairs = parts[1].split('&');
1261
+ for (i = 0; i < pairs.length; i++) {
1262
+ pair = pairs[i].split('=');
1263
+ params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1]));
1264
+ }
1265
+ }
1266
+ return params;
1267
+ },
1268
+
1269
+ _parseParamPair: function(params, key, value) {
1270
+ if (params[key]) {
1271
+ if (_isArray(params[key])) {
1272
+ params[key].push(value);
1273
+ } else {
1274
+ params[key] = [params[key], value];
1275
+ }
1276
+ } else {
1277
+ params[key] = value;
1278
+ }
1279
+ return params;
1280
+ },
1281
+
1282
+ _listen: function(name, callback) {
1283
+ return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
1284
+ },
1285
+
1286
+ _unlisten: function(name, callback) {
1287
+ return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
1288
+ }
1289
+
1290
+ });
1291
+
1292
+ // `Sammy.RenderContext` is an object that makes sequential template loading,
1293
+ // rendering and interpolation seamless even when dealing with asyncronous
1294
+ // operations.
1295
+ //
1296
+ // `RenderContext` objects are not usually created directly, rather they are
1297
+ // instatiated from an `Sammy.EventContext` by using `render()`, `load()` or
1298
+ // `partial()` which all return `RenderContext` objects.
1299
+ //
1300
+ // `RenderContext` methods always returns a modified `RenderContext`
1301
+ // for chaining (like jQuery itself).
1302
+ //
1303
+ // The core magic is in the `then()` method which puts the callback passed as
1304
+ // an argument into a queue to be executed once the previous callback is complete.
1305
+ // All the methods of `RenderContext` are wrapped in `then()` which allows you
1306
+ // to queue up methods by chaining, but maintaing a guarunteed execution order
1307
+ // even with remote calls to fetch templates.
1308
+ //
1309
+ Sammy.RenderContext = function(event_context) {
1310
+ this.event_context = event_context;
1311
+ this.callbacks = [];
1312
+ this.previous_content = null;
1313
+ this.content = null;
1314
+ this.next_engine = false;
1315
+ this.waiting = false;
1316
+ };
1317
+
1318
+ Sammy.RenderContext.prototype = $.extend({}, Sammy.Object.prototype, {
1319
+
1320
+ // The "core" of the `RenderContext` object, adds the `callback` to the
1321
+ // queue. If the context is `waiting` (meaning an async operation is happening)
1322
+ // then the callback will be executed in order, once the other operations are
1323
+ // complete. If there is no currently executing operation, the `callback`
1324
+ // is executed immediately.
1325
+ //
1326
+ // The value returned from the callback is stored in `content` for the
1327
+ // subsiquent operation. If you return `false`, the queue will pause, and
1328
+ // the next callback in the queue will not be executed until `next()` is
1329
+ // called. This allows for the guarunteed order of execution while working
1330
+ // with async operations.
1331
+ //
1332
+ // If then() is passed a string instead of a function, the string is looked
1333
+ // up as a helper method on the event context.
1334
+ //
1335
+ // ### Example
1336
+ //
1337
+ // this.get('#/', function() {
1338
+ // // initialize the RenderContext
1339
+ // // Even though `load()` executes async, the next `then()`
1340
+ // // wont execute until the load finishes
1341
+ // this.load('myfile.txt')
1342
+ // .then(function(content) {
1343
+ // // the first argument to then is the content of the
1344
+ // // prev operation
1345
+ // $('#main').html(content);
1346
+ // });
1347
+ // });
1348
+ //
1349
+ then: function(callback) {
1350
+ if (!_isFunction(callback)) {
1351
+ // if a string is passed to then, assume we want to call
1352
+ // a helper on the event context in its context
1353
+ if (typeof callback === 'string' && callback in this.event_context) {
1354
+ var helper = this.event_context[callback];
1355
+ callback = function(content) {
1356
+ return helper.apply(this.event_context, [content]);
1357
+ };
1358
+ } else {
1359
+ return this;
1360
+ }
1361
+ }
1362
+ var context = this;
1363
+ if (this.waiting) {
1364
+ this.callbacks.push(callback);
1365
+ } else {
1366
+ this.wait();
1367
+ window.setTimeout(function() {
1368
+ var returned = callback.apply(context, [context.content, context.previous_content]);
1369
+ if (returned !== false) {
1370
+ context.next(returned);
1371
+ }
1372
+ }, 13);
1373
+ }
1374
+ return this;
1375
+ },
1376
+
1377
+ // Pause the `RenderContext` queue. Combined with `next()` allows for async
1378
+ // operations.
1379
+ //
1380
+ // ### Example
1381
+ //
1382
+ // this.get('#/', function() {
1383
+ // this.load('mytext.json')
1384
+ // .then(function(content) {
1385
+ // var context = this,
1386
+ // data = JSON.parse(content);
1387
+ // // pause execution
1388
+ // context.wait();
1389
+ // // post to a url
1390
+ // $.post(data.url, {}, function(response) {
1391
+ // context.next(JSON.parse(response));
1392
+ // });
1393
+ // })
1394
+ // .then(function(data) {
1395
+ // // data is json from the previous post
1396
+ // $('#message').text(data.status);
1397
+ // });
1398
+ // });
1399
+ wait: function() {
1400
+ this.waiting = true;
1401
+ },
1402
+
1403
+ // Resume the queue, setting `content` to be used in the next operation.
1404
+ // See `wait()` for an example.
1405
+ next: function(content) {
1406
+ this.waiting = false;
1407
+ if (typeof content !== 'undefined') {
1408
+ this.previous_content = this.content;
1409
+ this.content = content;
1410
+ }
1411
+ if (this.callbacks.length > 0) {
1412
+ this.then(this.callbacks.shift());
1413
+ }
1414
+ },
1415
+
1416
+ // Load a template into the context.
1417
+ // The `location` can either be a string specifiying the remote path to the
1418
+ // file, a jQuery object, or a DOM element.
1419
+ //
1420
+ // No interpolation happens by default, the content is stored in
1421
+ // `content`.
1422
+ //
1423
+ // In the case of a path, unless the option `{cache: false}` is passed the
1424
+ // data is stored in the app's `templateCache()`.
1425
+ //
1426
+ // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
1427
+ // This is useful for nesting templates as part of the initial page load wrapped
1428
+ // in invisible elements or `<script>` tags. With template paths, the template
1429
+ // engine is looked up by the extension. For DOM/jQuery embedded templates,
1430
+ // this isnt possible, so there are a couple of options:
1431
+ //
1432
+ // * pass an `{engine:}` option.
1433
+ // * define the engine in the `data-engine` attribute of the passed node.
1434
+ // * just store the raw template data and use `interpolate()` manually
1435
+ //
1436
+ // If a `callback` is passed it is executed after the template load.
1437
+ load: function(location, options, callback) {
1438
+ var context = this;
1439
+ return this.then(function() {
1440
+ var should_cache, cached, is_json, location_array;
1441
+ if (_isFunction(options)) {
1442
+ callback = options;
1443
+ options = {};
1444
+ } else {
1445
+ options = $.extend({}, options);
1446
+ }
1447
+ if (callback) { this.then(callback); }
1448
+ if (typeof location === 'string') {
1449
+ // it's a path
1450
+ is_json = (location.match(/\.json$/) || options.json);
1451
+ should_cache = ((is_json && options.cache === true) || options.cache !== false);
1452
+ context.next_engine = context.event_context.engineFor(location);
1453
+ delete options.cache;
1454
+ delete options.json;
1455
+ if (options.engine) {
1456
+ context.next_engine = options.engine;
1457
+ delete options.engine;
1458
+ }
1459
+ if (should_cache && (cached = this.event_context.app.templateCache(location))) {
1460
+ return cached;
1461
+ }
1462
+ this.wait();
1463
+ $.ajax($.extend({
1464
+ url: location,
1465
+ data: {},
1466
+ dataType: is_json ? 'json' : null,
1467
+ type: 'get',
1468
+ success: function(data) {
1469
+ if (should_cache) {
1470
+ context.event_context.app.templateCache(location, data);
1471
+ }
1472
+ context.next(data);
1473
+ }
1474
+ }, options));
1475
+ return false;
1476
+ } else {
1477
+ // it's a dom/jQuery
1478
+ if (location.nodeType) {
1479
+ return location.innerHTML;
1480
+ }
1481
+ if (location.selector) {
1482
+ // it's a jQuery
1483
+ context.next_engine = location.attr('data-engine');
1484
+ if (options.clone === false) {
1485
+ return location.remove()[0].innerHTML.toString();
1486
+ } else {
1487
+ return location[0].innerHTML.toString();
1488
+ }
1489
+ }
1490
+ }
1491
+ });
1492
+ },
1493
+
1494
+ // `load()` a template and then `interpolate()` it with data.
1495
+ //
1496
+ // ### Example
1497
+ //
1498
+ // this.get('#/', function() {
1499
+ // this.render('mytemplate.template', {name: 'test'});
1500
+ // });
1501
+ //
1502
+ render: function(location, data, callback) {
1503
+ if (_isFunction(location) && !data) {
1504
+ return this.then(location);
1505
+ } else {
1506
+ if (!data && this.content) { data = this.content; }
1507
+ return this.load(location)
1508
+ .interpolate(data, location)
1509
+ .then(callback);
1510
+ }
1511
+ },
1512
+
1513
+ // `render()` the the `location` with `data` and then `swap()` the
1514
+ // app's `$element` with the rendered content.
1515
+ partial: function(location, data) {
1516
+ return this.render(location, data).swap();
1517
+ },
1518
+
1519
+ // defers the call of function to occur in order of the render queue.
1520
+ // The function can accept any number of arguments as long as the last
1521
+ // argument is a callback function. This is useful for putting arbitrary
1522
+ // asynchronous functions into the queue. The content passed to the
1523
+ // callback is passed as `content` to the next item in the queue.
1524
+ //
1525
+ // === Example
1526
+ //
1527
+ // this.send($.getJSON, '/app.json')
1528
+ // .then(function(json) {
1529
+ // $('#message).text(json['message']);
1530
+ // });
1531
+ //
1532
+ //
1533
+ send: function() {
1534
+ var context = this,
1535
+ args = _makeArray(arguments),
1536
+ fun = args.shift();
1537
+
1538
+ if (_isArray(args[0])) { args = args[0]; }
1539
+
1540
+ return this.then(function(content) {
1541
+ args.push(function(response) { context.next(response); });
1542
+ context.wait();
1543
+ fun.apply(fun, args);
1544
+ return false;
1545
+ });
1546
+ },
1547
+
1548
+ // itterates over an array, applying the callback for each item item. the
1549
+ // callback takes the same style of arguments as `jQuery.each()` (index, item).
1550
+ // The return value of each callback is collected as a single string and stored
1551
+ // as `content` to be used in the next iteration of the `RenderContext`.
1552
+ collect: function(array, callback, now) {
1553
+ var context = this;
1554
+ var coll = function() {
1555
+ if (_isFunction(array)) {
1556
+ callback = array;
1557
+ array = this.content;
1558
+ }
1559
+ var contents = [], doms = false;
1560
+ $.each(array, function(i, item) {
1561
+ var returned = callback.apply(context, [i, item]);
1562
+ if (returned.jquery && returned.length == 1) {
1563
+ returned = returned[0];
1564
+ doms = true;
1565
+ }
1566
+ contents.push(returned);
1567
+ return returned;
1568
+ });
1569
+ return doms ? contents : contents.join('');
1570
+ };
1571
+ return now ? coll() : this.then(coll);
1572
+ },
1573
+
1574
+ // loads a template, and then interpolates it for each item in the `data`
1575
+ // array. If a callback is passed, it will call the callback with each
1576
+ // item in the array _after_ interpolation
1577
+ renderEach: function(location, name, data, callback) {
1578
+ if (_isArray(name)) {
1579
+ callback = data;
1580
+ data = name;
1581
+ name = null;
1582
+ }
1583
+ return this.load(location).then(function(content) {
1584
+ var rctx = this;
1585
+ if (!data) {
1586
+ data = _isArray(this.previous_content) ? this.previous_content : [];
1587
+ }
1588
+ if (callback) {
1589
+ $.each(data, function(i, value) {
1590
+ var idata = {}, engine = this.next_engine || location;
1591
+ name ? (idata[name] = value) : (idata = value);
1592
+ callback(value, rctx.event_context.interpolate(content, idata, engine));
1593
+ });
1594
+ } else {
1595
+ return this.collect(data, function(i, value) {
1596
+ var idata = {}, engine = this.next_engine || location;
1597
+ name ? (idata[name] = value) : (idata = value);
1598
+ return this.event_context.interpolate(content, idata, engine);
1599
+ }, true);
1600
+ }
1601
+ });
1602
+ },
1603
+
1604
+ // uses the previous loaded `content` and the `data` object to interpolate
1605
+ // a template. `engine` defines the templating/interpolation method/engine
1606
+ // that should be used. If `engine` is not passed, the `next_engine` is
1607
+ // used. If `retain` is `true`, the final interpolated data is appended to
1608
+ // the `previous_content` instead of just replacing it.
1609
+ interpolate: function(data, engine, retain) {
1610
+ var context = this;
1611
+ return this.then(function(content, prev) {
1612
+ if (!data && prev) { data = prev; }
1613
+ if (this.next_engine) {
1614
+ engine = this.next_engine;
1615
+ this.next_engine = false;
1616
+ }
1617
+ var rendered = context.event_context.interpolate(content, data, engine);
1618
+ return retain ? prev + rendered : rendered;
1619
+ });
1620
+ },
1621
+
1622
+ // executes `EventContext#swap()` with the `content`
1623
+ swap: function() {
1624
+ return this.then(function(content) {
1625
+ this.event_context.swap(content);
1626
+ }).trigger('changed', {});
1627
+ },
1628
+
1629
+ // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
1630
+ appendTo: function(selector) {
1631
+ return this.then(function(content) {
1632
+ $(selector).append(content);
1633
+ }).trigger('changed', {});
1634
+ },
1635
+
1636
+ // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
1637
+ prependTo: function(selector) {
1638
+ return this.then(function(content) {
1639
+ $(selector).prepend(content);
1640
+ }).trigger('changed', {});
1641
+ },
1642
+
1643
+ // Replaces the `$(selector)` using `html()` with the previously loaded
1644
+ // `content`
1645
+ replace: function(selector) {
1646
+ return this.then(function(content) {
1647
+ $(selector).html(content);
1648
+ }).trigger('changed', {});
1649
+ },
1650
+
1651
+ // trigger the event in the order of the event context. Same semantics
1652
+ // as `Sammy.EventContext#trigger()`. If data is ommitted, `content`
1653
+ // is sent as `{content: content}`
1654
+ trigger: function(name, data) {
1655
+ return this.then(function(content) {
1656
+ if (typeof data == 'undefined') { data = {content: content}; }
1657
+ this.event_context.trigger(name, data);
1658
+ });
1659
+ }
1660
+
1661
+ });
1662
+
1663
+ // `Sammy.EventContext` objects are created every time a route is run or a
1664
+ // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
1665
+ // This within these callbacks the special methods of `EventContext` are available.
1666
+ //
1667
+ // ### Example
1668
+ //
1669
+ // $.sammy(function() {
1670
+ // // The context here is this Sammy.Application
1671
+ // this.get('#/:name', function() {
1672
+ // // The context here is a new Sammy.EventContext
1673
+ // if (this.params['name'] == 'sammy') {
1674
+ // this.partial('name.html.erb', {name: 'Sammy'});
1675
+ // } else {
1676
+ // this.redirect('#/somewhere-else')
1677
+ // }
1678
+ // });
1679
+ // });
1680
+ //
1681
+ // Initialize a new EventContext
1682
+ //
1683
+ // ### Arguments
1684
+ //
1685
+ // * `app` The `Sammy.Application` this event is called within.
1686
+ // * `verb` The verb invoked to run this context/route.
1687
+ // * `path` The string path invoked to run this context/route.
1688
+ // * `params` An Object of optional params to pass to the context. Is converted
1689
+ // to a `Sammy.Object`.
1690
+ // * `target` a DOM element that the event that holds this context originates
1691
+ // from. For post, put and del routes, this is the form element that triggered
1692
+ // the route.
1693
+ //
1694
+ Sammy.EventContext = function(app, verb, path, params, target) {
1695
+ this.app = app;
1696
+ this.verb = verb;
1697
+ this.path = path;
1698
+ this.params = new Sammy.Object(params);
1699
+ this.target = target;
1700
+ };
1701
+
1702
+ Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
1703
+
1704
+ // A shortcut to the app's `$element()`
1705
+ $element: function() {
1706
+ return this.app.$element(_makeArray(arguments).shift());
1707
+ },
1708
+
1709
+ // Look up a templating engine within the current app and context.
1710
+ // `engine` can be one of the following:
1711
+ //
1712
+ // * a function: should conform to `function(content, data) { return interploated; }`
1713
+ // * a template path: 'template.ejs', looks up the extension to match to
1714
+ // the `ejs()` helper
1715
+ // * a string referering to the helper: "mustache" => `mustache()`
1716
+ //
1717
+ // If no engine is found, use the app's default `template_engine`
1718
+ //
1719
+ engineFor: function(engine) {
1720
+ var context = this, engine_match;
1721
+ // if path is actually an engine function just return it
1722
+ if (_isFunction(engine)) { return engine; }
1723
+ // lookup engine name by path extension
1724
+ engine = (engine || context.app.template_engine).toString();
1725
+ if ((engine_match = engine.match(/\.([^\.]+)$/))) {
1726
+ engine = engine_match[1];
1727
+ }
1728
+ // set the engine to the default template engine if no match is found
1729
+ if (engine && _isFunction(context[engine])) {
1730
+ return context[engine];
1731
+ }
1732
+
1733
+ if (context.app.template_engine) {
1734
+ return this.engineFor(context.app.template_engine);
1735
+ }
1736
+ return function(content, data) { return content; };
1737
+ },
1738
+
1739
+ // using the template `engine` found with `engineFor()`, interpolate the
1740
+ // `data` into `content`
1741
+ interpolate: function(content, data, engine) {
1742
+ return this.engineFor(engine).apply(this, [content, data]);
1743
+ },
1744
+
1745
+ // Create and return a `Sammy.RenderContext` calling `render()` on it.
1746
+ // Loads the template and interpolate the data, however does not actual
1747
+ // place it in the DOM.
1748
+ //
1749
+ // ### Example
1750
+ //
1751
+ // // mytemplate.mustache <div class="name">{{name}}</div>
1752
+ // render('mytemplate.mustache', {name: 'quirkey'});
1753
+ // // sets the `content` to <div class="name">quirkey</div>
1754
+ // render('mytemplate.mustache', {name: 'quirkey'})
1755
+ // .appendTo('ul');
1756
+ // // appends the rendered content to $('ul')
1757
+ //
1758
+ render: function(location, data, callback) {
1759
+ return new Sammy.RenderContext(this).render(location, data, callback);
1760
+ },
1761
+
1762
+ // Create and return a `Sammy.RenderContext` calling `renderEach()` on it.
1763
+ // Loads the template and interpolates the data for each item,
1764
+ // however does not actual place it in the DOM.
1765
+ //
1766
+ // ### Example
1767
+ //
1768
+ // // mytemplate.mustache <div class="name">{{name}}</div>
1769
+ // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}])
1770
+ // // sets the `content` to <div class="name">quirkey</div><div class="name">endor</div>
1771
+ // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}]).appendTo('ul');
1772
+ // // appends the rendered content to $('ul')
1773
+ //
1774
+ renderEach: function(location, name, data, callback) {
1775
+ return new Sammy.RenderContext(this).renderEach(location, name, data, callback);
1776
+ },
1777
+
1778
+ // create a new `Sammy.RenderContext` calling `load()` with `location` and
1779
+ // `options`. Called without interpolation or placement, this allows for
1780
+ // preloading/caching the templates.
1781
+ load: function(location, options, callback) {
1782
+ return new Sammy.RenderContext(this).load(location, options, callback);
1783
+ },
1784
+
1785
+ // `render()` the the `location` with `data` and then `swap()` the
1786
+ // app's `$element` with the rendered content.
1787
+ partial: function(location, data) {
1788
+ return new Sammy.RenderContext(this).partial(location, data);
1789
+ },
1790
+
1791
+ // create a new `Sammy.RenderContext` calling `send()` with an arbitrary
1792
+ // function
1793
+ send: function() {
1794
+ var rctx = new Sammy.RenderContext(this);
1795
+ return rctx.send.apply(rctx, arguments);
1796
+ },
1797
+
1798
+ // Changes the location of the current window. If `to` begins with
1799
+ // '#' it only changes the document's hash. If passed more than 1 argument
1800
+ // redirect will join them together with forward slashes.
1801
+ //
1802
+ // ### Example
1803
+ //
1804
+ // redirect('#/other/route');
1805
+ // // equivilent to
1806
+ // redirect('#', 'other', 'route');
1807
+ //
1808
+ redirect: function() {
1809
+ var to, args = _makeArray(arguments),
1810
+ current_location = this.app.getLocation();
1811
+ if (args.length > 1) {
1812
+ args.unshift('/');
1813
+ to = this.join.apply(this, args);
1814
+ } else {
1815
+ to = args[0];
1816
+ }
1817
+ this.trigger('redirect', {to: to});
1818
+ this.app.last_location = [this.verb, this.path];
1819
+ this.app.setLocation(to);
1820
+ if (current_location == to) {
1821
+ this.app.trigger('location-changed');
1822
+ }
1823
+ },
1824
+
1825
+ // Triggers events on `app` within the current context.
1826
+ trigger: function(name, data) {
1827
+ if (typeof data == 'undefined') { data = {}; }
1828
+ if (!data.context) { data.context = this; }
1829
+ return this.app.trigger(name, data);
1830
+ },
1831
+
1832
+ // A shortcut to app's `eventNamespace()`
1833
+ eventNamespace: function() {
1834
+ return this.app.eventNamespace();
1835
+ },
1836
+
1837
+ // A shortcut to app's `swap()`
1838
+ swap: function(contents) {
1839
+ return this.app.swap(contents);
1840
+ },
1841
+
1842
+ // Raises a possible `notFound()` error for the current path.
1843
+ notFound: function() {
1844
+ return this.app.notFound(this.verb, this.path);
1845
+ },
1846
+
1847
+ // Default JSON parsing uses jQuery's `parseJSON()`. Include `Sammy.JSON`
1848
+ // plugin for the more conformant "crockford special".
1849
+ json: function(string) {
1850
+ return $.parseJSON(string);
1851
+ },
1852
+
1853
+ // //=> Sammy.EventContext: get #/ {}
1854
+ toString: function() {
1855
+ return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
1856
+ }
1857
+
1858
+ });
1859
+
1860
+ // An alias to Sammy
1861
+ $.sammy = window.Sammy = Sammy;
1862
+
1863
+ })(jQuery, window);