h2ocube_rails_assets 0.0.19 → 0.0.20

Sign up to get free protection for your applications and to get access to all the features.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -0
  3. data/README.md +1 -0
  4. data/Vendorfile +196 -0
  5. data/h2ocube_rails_assets.gemspec +3 -4
  6. data/lib/h2ocube_rails_assets.rb +8 -6
  7. data/test/jquery_test.rb +1 -1
  8. data/test/turbolinks_test.rb +1 -3
  9. data/vendor/assets/images/jquery.fancybox/fancybox_loading.gif +0 -0
  10. data/vendor/assets/images/jquery.fancybox/fancybox_loading@2x.gif +0 -0
  11. data/vendor/assets/images/jquery.fancybox/fancybox_sprite@2x.png +0 -0
  12. data/vendor/assets/javascripts/backbone.js +4 -1571
  13. data/vendor/assets/javascripts/bootstrap.js +6 -2276
  14. data/vendor/assets/javascripts/highcharts.js +272 -15281
  15. data/vendor/assets/javascripts/jasny-bootstrap.js +7 -3060
  16. data/vendor/assets/javascripts/jquery/1.10.js +6 -9807
  17. data/vendor/assets/javascripts/jquery/1.8.js +2 -9472
  18. data/vendor/assets/javascripts/jquery/1.9.js +5 -9597
  19. data/vendor/assets/javascripts/jquery/2.0.js +5 -8841
  20. data/vendor/assets/javascripts/jquery.cookie.js +26 -23
  21. data/vendor/assets/javascripts/jquery.fancybox.js +46 -1983
  22. data/vendor/assets/javascripts/jquery.fileupload.js +1329 -4
  23. data/vendor/assets/javascripts/jquery.iframe-transport.js +24 -4
  24. data/vendor/assets/javascripts/jquery.js +1 -1
  25. data/vendor/assets/javascripts/jquery.lazyload.js +3 -216
  26. data/vendor/assets/javascripts/jquery.mobile.js +7 -11092
  27. data/vendor/assets/javascripts/jquery.pnotify.js +29 -903
  28. data/vendor/assets/javascripts/jquery.timeago.coffee +2 -4
  29. data/vendor/assets/javascripts/jquery.turbolinks.coffee +40 -51
  30. data/vendor/assets/javascripts/jquery.ui/jquery.ui.accordion.js +4 -572
  31. data/vendor/assets/javascripts/jquery.ui/jquery.ui.autocomplete.js +4 -610
  32. data/vendor/assets/javascripts/jquery.ui/jquery.ui.button.js +4 -419
  33. data/vendor/assets/javascripts/jquery.ui/jquery.ui.core.js +4 -320
  34. data/vendor/assets/javascripts/jquery.ui/jquery.ui.datepicker.js +5 -2050
  35. data/vendor/assets/javascripts/jquery.ui/jquery.ui.dialog.js +4 -808
  36. data/vendor/assets/javascripts/jquery.ui/jquery.ui.draggable.js +4 -933
  37. data/vendor/assets/javascripts/jquery.ui/jquery.ui.droppable.js +4 -372
  38. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-blind.js +4 -82
  39. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-bounce.js +4 -113
  40. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-clip.js +4 -67
  41. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-drop.js +4 -65
  42. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-explode.js +4 -97
  43. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-fade.js +4 -30
  44. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-fold.js +4 -76
  45. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-highlight.js +4 -50
  46. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-pulsate.js +4 -63
  47. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-scale.js +4 -318
  48. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-shake.js +4 -74
  49. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-slide.js +4 -64
  50. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect-transfer.js +4 -47
  51. data/vendor/assets/javascripts/jquery.ui/jquery.ui.effect.js +4 -1289
  52. data/vendor/assets/javascripts/jquery.ui/jquery.ui.menu.js +4 -621
  53. data/vendor/assets/javascripts/jquery.ui/jquery.ui.mouse.js +4 -169
  54. data/vendor/assets/javascripts/jquery.ui/jquery.ui.position.js +4 -497
  55. data/vendor/assets/javascripts/jquery.ui/jquery.ui.progressbar.js +4 -145
  56. data/vendor/assets/javascripts/jquery.ui/jquery.ui.resizable.js +4 -968
  57. data/vendor/assets/javascripts/jquery.ui/jquery.ui.selectable.js +4 -277
  58. data/vendor/assets/javascripts/jquery.ui/jquery.ui.slider.js +4 -672
  59. data/vendor/assets/javascripts/jquery.ui/jquery.ui.sortable.js +4 -1282
  60. data/vendor/assets/javascripts/jquery.ui/jquery.ui.spinner.js +4 -493
  61. data/vendor/assets/javascripts/jquery.ui/jquery.ui.tabs.js +4 -846
  62. data/vendor/assets/javascripts/jquery.ui/jquery.ui.tooltip.js +4 -402
  63. data/vendor/assets/javascripts/jquery.ui/jquery.ui.widget.js +4 -521
  64. data/vendor/assets/javascripts/jquery.validate.js +2 -1207
  65. data/vendor/assets/javascripts/lazyload.js +4 -391
  66. data/vendor/assets/javascripts/sammy.js +5 -2117
  67. data/vendor/assets/javascripts/underscore.js +4 -1224
  68. data/vendor/assets/javascripts/zepto.js +1 -1564
  69. data/vendor/assets/stylesheets/bootstrap.responsive.css +2 -1102
  70. data/vendor/assets/stylesheets/bootstrap.scss +2 -6151
  71. data/vendor/assets/stylesheets/jasny-bootstrap.responsive.css +2 -1263
  72. data/vendor/assets/stylesheets/jasny-bootstrap.scss +2 -7591
  73. data/vendor/assets/stylesheets/jquery.fancybox.scss +27 -2
  74. data/vendor/assets/stylesheets/jquery.mobile.scss +2 -3356
  75. data/vendor/assets/stylesheets/jquery.ui.scss +2 -1184
  76. metadata +43 -19
  77. data/vendor/assets/images/jquery.mobile/ajax-loader.gif +0 -0
  78. data/vendor/assets/images/jquery.mobile/icons-18-black.png +0 -0
  79. data/vendor/assets/images/jquery.mobile/icons-18-white.png +0 -0
  80. data/vendor/assets/images/jquery.mobile/icons-36-black.png +0 -0
  81. data/vendor/assets/images/jquery.mobile/icons-36-white.png +0 -0
  82. data/vendor/assets/javascripts/_jquery.fileupload.js +0 -1164
  83. data/vendor/assets/javascripts/zepto/fx_methods.js +0 -71
@@ -1,391 +1,4 @@
1
- /*jslint browser: true, eqeqeq: true, bitwise: true, newcap: true, immed: true, regexp: false */
2
-
3
- /**
4
- LazyLoad makes it easy and painless to lazily load one or more external
5
- JavaScript or CSS files on demand either during or after the rendering of a web
6
- page.
7
-
8
- Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile
9
- Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and
10
- are not officially supported.
11
-
12
- Visit https://github.com/rgrove/lazyload/ for more info.
13
-
14
- Copyright (c) 2011 Ryan Grove <ryan@wonko.com>
15
- All rights reserved.
16
-
17
- Permission is hereby granted, free of charge, to any person obtaining a copy of
18
- this software and associated documentation files (the 'Software'), to deal in
19
- the Software without restriction, including without limitation the rights to
20
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
21
- the Software, and to permit persons to whom the Software is furnished to do so,
22
- subject to the following conditions:
23
-
24
- The above copyright notice and this permission notice shall be included in all
25
- copies or substantial portions of the Software.
26
-
27
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
29
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
30
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
31
- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
32
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33
-
34
- @module lazyload
35
- @class LazyLoad
36
- @static
37
- @version 2.0.3 (git)
38
- */
39
-
40
- LazyLoad = (function (doc) {
41
- // -- Private Variables ------------------------------------------------------
42
-
43
- // User agent and feature test information.
44
- var env,
45
-
46
- // Reference to the <head> element (populated lazily).
47
- head,
48
-
49
- // Requests currently in progress, if any.
50
- pending = {},
51
-
52
- // Number of times we've polled to check whether a pending stylesheet has
53
- // finished loading. If this gets too high, we're probably stalled.
54
- pollCount = 0,
55
-
56
- // Queued requests.
57
- queue = {css: [], js: []},
58
-
59
- // Reference to the browser's list of stylesheets.
60
- styleSheets = doc.styleSheets;
61
-
62
- // -- Private Methods --------------------------------------------------------
63
-
64
- /**
65
- Creates and returns an HTML element with the specified name and attributes.
66
-
67
- @method createNode
68
- @param {String} name element name
69
- @param {Object} attrs name/value mapping of element attributes
70
- @return {HTMLElement}
71
- @private
72
- */
73
- function createNode(name, attrs) {
74
- var node = doc.createElement(name), attr;
75
-
76
- for (attr in attrs) {
77
- if (attrs.hasOwnProperty(attr)) {
78
- node.setAttribute(attr, attrs[attr]);
79
- }
80
- }
81
-
82
- return node;
83
- }
84
-
85
- /**
86
- Called when the current pending resource of the specified type has finished
87
- loading. Executes the associated callback (if any) and loads the next
88
- resource in the queue.
89
-
90
- @method finish
91
- @param {String} type resource type ('css' or 'js')
92
- @private
93
- */
94
- function finish(type) {
95
- var p = pending[type],
96
- callback,
97
- urls;
98
-
99
- if (p) {
100
- callback = p.callback;
101
- urls = p.urls;
102
-
103
- urls.shift();
104
- pollCount = 0;
105
-
106
- // If this is the last of the pending URLs, execute the callback and
107
- // start the next request in the queue (if any).
108
- if (!urls.length) {
109
- callback && callback.call(p.context, p.obj);
110
- pending[type] = null;
111
- queue[type].length && load(type);
112
- }
113
- }
114
- }
115
-
116
- /**
117
- Populates the <code>env</code> variable with user agent and feature test
118
- information.
119
-
120
- @method getEnv
121
- @private
122
- */
123
- function getEnv() {
124
- var ua = navigator.userAgent;
125
-
126
- env = {
127
- // True if this browser supports disabling async mode on dynamically
128
- // created script nodes. See
129
- // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
130
- async: doc.createElement('script').async === true
131
- };
132
-
133
- (env.webkit = /AppleWebKit\//.test(ua))
134
- || (env.ie = /MSIE/.test(ua))
135
- || (env.opera = /Opera/.test(ua))
136
- || (env.gecko = /Gecko\//.test(ua))
137
- || (env.unknown = true);
138
- }
139
-
140
- /**
141
- Loads the specified resources, or the next resource of the specified type
142
- in the queue if no resources are specified. If a resource of the specified
143
- type is already being loaded, the new request will be queued until the
144
- first request has been finished.
145
-
146
- When an array of resource URLs is specified, those URLs will be loaded in
147
- parallel if it is possible to do so while preserving execution order. All
148
- browsers support parallel loading of CSS, but only Firefox and Opera
149
- support parallel loading of scripts. In other browsers, scripts will be
150
- queued and loaded one at a time to ensure correct execution order.
151
-
152
- @method load
153
- @param {String} type resource type ('css' or 'js')
154
- @param {String|Array} urls (optional) URL or array of URLs to load
155
- @param {Function} callback (optional) callback function to execute when the
156
- resource is loaded
157
- @param {Object} obj (optional) object to pass to the callback function
158
- @param {Object} context (optional) if provided, the callback function will
159
- be executed in this object's context
160
- @private
161
- */
162
- function load(type, urls, callback, obj, context) {
163
- var _finish = function () { finish(type); },
164
- isCSS = type === 'css',
165
- nodes = [],
166
- i, len, node, p, pendingUrls, url;
167
-
168
- env || getEnv();
169
-
170
- if (urls) {
171
- // If urls is a string, wrap it in an array. Otherwise assume it's an
172
- // array and create a copy of it so modifications won't be made to the
173
- // original.
174
- urls = typeof urls === 'string' ? [urls] : urls.concat();
175
-
176
- // Create a request object for each URL. If multiple URLs are specified,
177
- // the callback will only be executed after all URLs have been loaded.
178
- //
179
- // Sadly, Firefox and Opera are the only browsers capable of loading
180
- // scripts in parallel while preserving execution order. In all other
181
- // browsers, scripts must be loaded sequentially.
182
- //
183
- // All browsers respect CSS specificity based on the order of the link
184
- // elements in the DOM, regardless of the order in which the stylesheets
185
- // are actually downloaded.
186
- if (isCSS || env.async || env.gecko || env.opera) {
187
- // Load in parallel.
188
- queue[type].push({
189
- urls : urls,
190
- callback: callback,
191
- obj : obj,
192
- context : context
193
- });
194
- } else {
195
- // Load sequentially.
196
- for (i = 0, len = urls.length; i < len; ++i) {
197
- queue[type].push({
198
- urls : [urls[i]],
199
- callback: i === len - 1 ? callback : null, // callback is only added to the last URL
200
- obj : obj,
201
- context : context
202
- });
203
- }
204
- }
205
- }
206
-
207
- // If a previous load request of this type is currently in progress, we'll
208
- // wait our turn. Otherwise, grab the next item in the queue.
209
- if (pending[type] || !(p = pending[type] = queue[type].shift())) {
210
- return;
211
- }
212
-
213
- head || (head = doc.head || doc.getElementsByTagName('head')[0]);
214
- pendingUrls = p.urls;
215
-
216
- for (i = 0, len = pendingUrls.length; i < len; ++i) {
217
- url = pendingUrls[i];
218
-
219
- if (isCSS) {
220
- node = env.gecko ? createNode('style') : createNode('link', {
221
- href: url,
222
- rel : 'stylesheet'
223
- });
224
- } else {
225
- node = createNode('script', {src: url});
226
- node.async = false;
227
- }
228
-
229
- node.className = 'lazyload';
230
- node.setAttribute('charset', 'utf-8');
231
-
232
- if (env.ie && !isCSS) {
233
- node.onreadystatechange = function () {
234
- if (/loaded|complete/.test(node.readyState)) {
235
- node.onreadystatechange = null;
236
- _finish();
237
- }
238
- };
239
- } else if (isCSS && (env.gecko || env.webkit)) {
240
- // Gecko and WebKit don't support the onload event on link nodes.
241
- if (env.webkit) {
242
- // In WebKit, we can poll for changes to document.styleSheets to
243
- // figure out when stylesheets have loaded.
244
- p.urls[i] = node.href; // resolve relative URLs (or polling won't work)
245
- pollWebKit();
246
- } else {
247
- // In Gecko, we can import the requested URL into a <style> node and
248
- // poll for the existence of node.sheet.cssRules. Props to Zach
249
- // Leatherman for calling my attention to this technique.
250
- node.innerHTML = '@import "' + url + '";';
251
- pollGecko(node);
252
- }
253
- } else {
254
- node.onload = node.onerror = _finish;
255
- }
256
-
257
- nodes.push(node);
258
- }
259
-
260
- for (i = 0, len = nodes.length; i < len; ++i) {
261
- head.appendChild(nodes[i]);
262
- }
263
- }
264
-
265
- /**
266
- Begins polling to determine when the specified stylesheet has finished loading
267
- in Gecko. Polling stops when all pending stylesheets have loaded or after 10
268
- seconds (to prevent stalls).
269
-
270
- Thanks to Zach Leatherman for calling my attention to the @import-based
271
- cross-domain technique used here, and to Oleg Slobodskoi for an earlier
272
- same-domain implementation. See Zach's blog for more details:
273
- http://www.zachleat.com/web/2010/07/29/load-css-dynamically/
274
-
275
- @method pollGecko
276
- @param {HTMLElement} node Style node to poll.
277
- @private
278
- */
279
- function pollGecko(node) {
280
- var hasRules;
281
-
282
- try {
283
- // We don't really need to store this value or ever refer to it again, but
284
- // if we don't store it, Closure Compiler assumes the code is useless and
285
- // removes it.
286
- hasRules = !!node.sheet.cssRules;
287
- } catch (ex) {
288
- // An exception means the stylesheet is still loading.
289
- pollCount += 1;
290
-
291
- if (pollCount < 200) {
292
- setTimeout(function () { pollGecko(node); }, 50);
293
- } else {
294
- // We've been polling for 10 seconds and nothing's happened. Stop
295
- // polling and finish the pending requests to avoid blocking further
296
- // requests.
297
- hasRules && finish('css');
298
- }
299
-
300
- return;
301
- }
302
-
303
- // If we get here, the stylesheet has loaded.
304
- finish('css');
305
- }
306
-
307
- /**
308
- Begins polling to determine when pending stylesheets have finished loading
309
- in WebKit. Polling stops when all pending stylesheets have loaded or after 10
310
- seconds (to prevent stalls).
311
-
312
- @method pollWebKit
313
- @private
314
- */
315
- function pollWebKit() {
316
- var css = pending.css, i;
317
-
318
- if (css) {
319
- i = styleSheets.length;
320
-
321
- // Look for a stylesheet matching the pending URL.
322
- while (--i >= 0) {
323
- if (styleSheets[i].href === css.urls[0]) {
324
- finish('css');
325
- break;
326
- }
327
- }
328
-
329
- pollCount += 1;
330
-
331
- if (css) {
332
- if (pollCount < 200) {
333
- setTimeout(pollWebKit, 50);
334
- } else {
335
- // We've been polling for 10 seconds and nothing's happened, which may
336
- // indicate that the stylesheet has been removed from the document
337
- // before it had a chance to load. Stop polling and finish the pending
338
- // request to prevent blocking further requests.
339
- finish('css');
340
- }
341
- }
342
- }
343
- }
344
-
345
- return {
346
-
347
- /**
348
- Requests the specified CSS URL or URLs and executes the specified
349
- callback (if any) when they have finished loading. If an array of URLs is
350
- specified, the stylesheets will be loaded in parallel and the callback
351
- will be executed after all stylesheets have finished loading.
352
-
353
- @method css
354
- @param {String|Array} urls CSS URL or array of CSS URLs to load
355
- @param {Function} callback (optional) callback function to execute when
356
- the specified stylesheets are loaded
357
- @param {Object} obj (optional) object to pass to the callback function
358
- @param {Object} context (optional) if provided, the callback function
359
- will be executed in this object's context
360
- @static
361
- */
362
- css: function (urls, callback, obj, context) {
363
- load('css', urls, callback, obj, context);
364
- },
365
-
366
- /**
367
- Requests the specified JavaScript URL or URLs and executes the specified
368
- callback (if any) when they have finished loading. If an array of URLs is
369
- specified and the browser supports it, the scripts will be loaded in
370
- parallel and the callback will be executed after all scripts have
371
- finished loading.
372
-
373
- Currently, only Firefox and Opera support parallel loading of scripts while
374
- preserving execution order. In other browsers, scripts will be
375
- queued and loaded one at a time to ensure correct execution order.
376
-
377
- @method js
378
- @param {String|Array} urls JS URL or array of JS URLs to load
379
- @param {Function} callback (optional) callback function to execute when
380
- the specified scripts are loaded
381
- @param {Object} obj (optional) object to pass to the callback function
382
- @param {Object} context (optional) if provided, the callback function
383
- will be executed in this object's context
384
- @static
385
- */
386
- js: function (urls, callback, obj, context) {
387
- load('js', urls, callback, obj, context);
388
- }
389
-
390
- };
391
- })(this.document);
1
+ LazyLoad=function(k){function p(b,a){var g=k.createElement(b),c;for(c in a)a.hasOwnProperty(c)&&g.setAttribute(c,a[c]);return g}function l(b){var a=m[b],c,f;if(a)c=a.callback,f=a.urls,f.shift(),h=0,f.length||(c&&c.call(a.context,a.obj),m[b]=null,n[b].length&&j(b))}function w(){var b=navigator.userAgent;c={async:k.createElement("script").async===!0};(c.webkit=/AppleWebKit\//.test(b))||(c.ie=/MSIE/.test(b))||(c.opera=/Opera/.test(b))||(c.gecko=/Gecko\//.test(b))||(c.unknown=!0)}function j(b,a,g,f,h){var j=
2
+ function(){l(b)},o=b==="css",q=[],d,i,e,r;c||w();if(a)if(a=typeof a==="string"?[a]:a.concat(),o||c.async||c.gecko||c.opera)n[b].push({urls:a,callback:g,obj:f,context:h});else{d=0;for(i=a.length;d<i;++d)n[b].push({urls:[a[d]],callback:d===i-1?g:null,obj:f,context:h})}if(!m[b]&&(r=m[b]=n[b].shift())){s||(s=k.head||k.getElementsByTagName("head")[0]);a=r.urls;d=0;for(i=a.length;d<i;++d)g=a[d],o?e=c.gecko?p("style"):p("link",{href:g,rel:"stylesheet"}):(e=p("script",{src:g}),e.async=!1),e.className="lazyload",
3
+ e.setAttribute("charset","utf-8"),c.ie&&!o?e.onreadystatechange=function(){if(/loaded|complete/.test(e.readyState))e.onreadystatechange=null,j()}:o&&(c.gecko||c.webkit)?c.webkit?(r.urls[d]=e.href,t()):(e.innerHTML='@import "'+g+'";',u(e)):e.onload=e.onerror=j,q.push(e);d=0;for(i=q.length;d<i;++d)s.appendChild(q[d])}}function u(b){var a;try{a=!!b.sheet.cssRules}catch(c){h+=1;h<200?setTimeout(function(){u(b)},50):a&&l("css");return}l("css")}function t(){var b=m.css,a;if(b){for(a=v.length;--a>=0;)if(v[a].href===
4
+ b.urls[0]){l("css");break}h+=1;b&&(h<200?setTimeout(t,50):l("css"))}}var c,s,m={},h=0,n={css:[],js:[]},v=k.styleSheets;return{css:function(b,a,c,f){j("css",b,a,c,f)},js:function(b,a,c,f){j("js",b,a,c,f)}}}(this.document);
@@ -1,2120 +1,8 @@
1
+ // -- Sammy.js -- /sammy.js
2
+ // http://sammyjs.org
3
+ // Version: 0.7.4
4
+ // Built: 2013-01-27 13:34:16 -0500
1
5
  // name: sammy
2
6
  // version: 0.7.4
3
-
4
7
  // Sammy.js / http://sammyjs.org
5
-
6
- (function($, window) {
7
- (function(factory){
8
- // Support module loading scenarios
9
- if (typeof define === 'function' && define.amd){
10
- // AMD Anonymous Module
11
- define(['jquery'], factory);
12
- } else {
13
- // No module loader (plain <script> tag) - put directly in global namespace
14
- $.sammy = window.Sammy = factory($);
15
- }
16
- })(function($){
17
-
18
- var Sammy,
19
- PATH_REPLACER = "([^\/]+)",
20
- PATH_NAME_MATCHER = /:([\w\d]+)/g,
21
- QUERY_STRING_MATCHER = /\?([^#]*)?$/,
22
- // mainly for making `arguments` an Array
23
- _makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); },
24
- // borrowed from jQuery
25
- _isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; },
26
- _isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; },
27
- _isRegExp = function( obj ) { return Object.prototype.toString.call(obj) === "[object RegExp]"; },
28
- _decode = function( str ) { return decodeURIComponent((str || '').replace(/\+/g, ' ')); },
29
- _encode = encodeURIComponent,
30
- _escapeHTML = function(s) {
31
- return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
32
- },
33
- _routeWrapper = function(verb) {
34
- return function() {
35
- return this.route.apply(this, [verb].concat(Array.prototype.slice.call(arguments)));
36
- };
37
- },
38
- _template_cache = {},
39
- _has_history = !!(window.history && history.pushState),
40
- loggers = [];
41
-
42
-
43
- // `Sammy` (also aliased as $.sammy) is not only the namespace for a
44
- // number of prototypes, its also a top level method that allows for easy
45
- // creation/management of `Sammy.Application` instances. There are a
46
- // number of different forms for `Sammy()` but each returns an instance
47
- // of `Sammy.Application`. When a new instance is created using
48
- // `Sammy` it is added to an Object called `Sammy.apps`. This
49
- // provides for an easy way to get at existing Sammy applications. Only one
50
- // instance is allowed per `element_selector` so when calling
51
- // `Sammy('selector')` multiple times, the first time will create
52
- // the application and the following times will extend the application
53
- // already added to that selector.
54
- //
55
- // ### Example
56
- //
57
- // // returns the app at #main or a new app
58
- // Sammy('#main')
59
- //
60
- // // equivalent to "new Sammy.Application", except appends to apps
61
- // Sammy();
62
- // Sammy(function() { ... });
63
- //
64
- // // extends the app at '#main' with function.
65
- // Sammy('#main', function() { ... });
66
- //
67
- Sammy = function() {
68
- var args = _makeArray(arguments),
69
- app, selector;
70
- Sammy.apps = Sammy.apps || {};
71
- if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
72
- return Sammy.apply(Sammy, ['body'].concat(args));
73
- } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
74
- app = Sammy.apps[selector] || new Sammy.Application();
75
- app.element_selector = selector;
76
- if (args.length > 0) {
77
- $.each(args, function(i, plugin) {
78
- app.use(plugin);
79
- });
80
- }
81
- // if the selector changes make sure the reference in Sammy.apps changes
82
- if (app.element_selector != selector) {
83
- delete Sammy.apps[selector];
84
- }
85
- Sammy.apps[app.element_selector] = app;
86
- return app;
87
- }
88
- };
89
-
90
- Sammy.VERSION = '0.7.4';
91
-
92
- // Add to the global logger pool. Takes a function that accepts an
93
- // unknown number of arguments and should print them or send them somewhere
94
- // The first argument is always a timestamp.
95
- Sammy.addLogger = function(logger) {
96
- loggers.push(logger);
97
- };
98
-
99
- // Sends a log message to each logger listed in the global
100
- // loggers pool. Can take any number of arguments.
101
- // Also prefixes the arguments with a timestamp.
102
- Sammy.log = function() {
103
- var args = _makeArray(arguments);
104
- args.unshift("[" + Date() + "]");
105
- $.each(loggers, function(i, logger) {
106
- logger.apply(Sammy, args);
107
- });
108
- };
109
-
110
- if (typeof window.console != 'undefined') {
111
- if (_isFunction(window.console.log.apply)) {
112
- Sammy.addLogger(function() {
113
- window.console.log.apply(window.console, arguments);
114
- });
115
- } else {
116
- Sammy.addLogger(function() {
117
- window.console.log(arguments);
118
- });
119
- }
120
- } else if (typeof console != 'undefined') {
121
- Sammy.addLogger(function() {
122
- console.log.apply(console, arguments);
123
- });
124
- }
125
-
126
- $.extend(Sammy, {
127
- makeArray: _makeArray,
128
- isFunction: _isFunction,
129
- isArray: _isArray
130
- });
131
-
132
- // Sammy.Object is the base for all other Sammy classes. It provides some useful
133
- // functionality, including cloning, iterating, etc.
134
- Sammy.Object = function(obj) { // constructor
135
- return $.extend(this, obj || {});
136
- };
137
-
138
- $.extend(Sammy.Object.prototype, {
139
-
140
- // Escape HTML in string, use in templates to prevent script injection.
141
- // Also aliased as `h()`
142
- escapeHTML: _escapeHTML,
143
- h: _escapeHTML,
144
-
145
- // Returns a copy of the object with Functions removed.
146
- toHash: function() {
147
- var json = {};
148
- $.each(this, function(k,v) {
149
- if (!_isFunction(v)) {
150
- json[k] = v;
151
- }
152
- });
153
- return json;
154
- },
155
-
156
- // Renders a simple HTML version of this Objects attributes.
157
- // Does not render functions.
158
- // For example. Given this Sammy.Object:
159
- //
160
- // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
161
- // s.toHTML()
162
- // //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
163
- //
164
- toHTML: function() {
165
- var display = "";
166
- $.each(this, function(k, v) {
167
- if (!_isFunction(v)) {
168
- display += "<strong>" + k + "</strong> " + v + "<br />";
169
- }
170
- });
171
- return display;
172
- },
173
-
174
- // Returns an array of keys for this object. If `attributes_only`
175
- // is true will not return keys that map to a `function()`
176
- keys: function(attributes_only) {
177
- var keys = [];
178
- for (var property in this) {
179
- if (!_isFunction(this[property]) || !attributes_only) {
180
- keys.push(property);
181
- }
182
- }
183
- return keys;
184
- },
185
-
186
- // Checks if the object has a value at `key` and that the value is not empty
187
- has: function(key) {
188
- return this[key] && $.trim(this[key].toString()) !== '';
189
- },
190
-
191
- // convenience method to join as many arguments as you want
192
- // by the first argument - useful for making paths
193
- join: function() {
194
- var args = _makeArray(arguments);
195
- var delimiter = args.shift();
196
- return args.join(delimiter);
197
- },
198
-
199
- // Shortcut to Sammy.log
200
- log: function() {
201
- Sammy.log.apply(Sammy, arguments);
202
- },
203
-
204
- // Returns a string representation of this object.
205
- // if `include_functions` is true, it will also toString() the
206
- // methods of this object. By default only prints the attributes.
207
- toString: function(include_functions) {
208
- var s = [];
209
- $.each(this, function(k, v) {
210
- if (!_isFunction(v) || include_functions) {
211
- s.push('"' + k + '": ' + v.toString());
212
- }
213
- });
214
- return "Sammy.Object: {" + s.join(',') + "}";
215
- }
216
- });
217
-
218
-
219
- // Return whether the event targets this window.
220
- Sammy.targetIsThisWindow = function targetIsThisWindow(event) {
221
- var targetWindow = $(event.target).attr('target');
222
- if ( !targetWindow || targetWindow === window.name || targetWindow === '_self' ) { return true; }
223
- if ( targetWindow === '_blank' ) { return false; }
224
- if ( targetWindow === 'top' && window === window.top ) { return true; }
225
- return false;
226
- };
227
-
228
-
229
- // The DefaultLocationProxy is the default location proxy for all Sammy applications.
230
- // A location proxy is a prototype that conforms to a simple interface. The purpose
231
- // of a location proxy is to notify the Sammy.Application its bound to when the location
232
- // or 'external state' changes.
233
- //
234
- // The `DefaultLocationProxy` watches for changes to the path of the current window and
235
- // is also able to set the path based on changes in the application. It does this by
236
- // using different methods depending on what is available in the current browser. In
237
- // the latest and greatest browsers it used the HTML5 History API and the `pushState`
238
- // `popState` events/methods. This allows you to use Sammy to serve a site behind normal
239
- // URI paths as opposed to the older default of hash (#) based routing. Because the server
240
- // can interpret the changed path on a refresh or re-entry, though, it requires additional
241
- // support on the server side. If you'd like to force disable HTML5 history support, please
242
- // use the `disable_push_state` setting on `Sammy.Application`. If pushState support
243
- // is enabled, `DefaultLocationProxy` also binds to all links on the page. If a link is clicked
244
- // that matches the current set of routes, the URL is changed using pushState instead of
245
- // fully setting the location and the app is notified of the change.
246
- //
247
- // If the browser does not have support for HTML5 History, `DefaultLocationProxy` automatically
248
- // falls back to the older hash based routing. The newest browsers (IE, Safari > 4, FF >= 3.6)
249
- // support a 'onhashchange' DOM event, thats fired whenever the location.hash changes.
250
- // In this situation the DefaultLocationProxy just binds to this event and delegates it to
251
- // the application. In the case of older browsers a poller is set up to track changes to the
252
- // hash.
253
- Sammy.DefaultLocationProxy = function(app, run_interval_every) {
254
- this.app = app;
255
- // set is native to false and start the poller immediately
256
- this.is_native = false;
257
- this.has_history = _has_history;
258
- this._startPolling(run_interval_every);
259
- };
260
-
261
- Sammy.DefaultLocationProxy.fullPath = function(location_obj) {
262
- // Bypass the `window.location.hash` attribute. If a question mark
263
- // appears in the hash IE6 will strip it and all of the following
264
- // characters from `window.location.hash`.
265
- var matches = location_obj.toString().match(/^[^#]*(#.+)$/);
266
- var hash = matches ? matches[1] : '';
267
- return [location_obj.pathname, location_obj.search, hash].join('');
268
- };
269
- $.extend(Sammy.DefaultLocationProxy.prototype , {
270
- // bind the proxy events to the current app.
271
- bind: function() {
272
- var proxy = this, app = this.app, lp = Sammy.DefaultLocationProxy;
273
- $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
274
- // if we receive a native hash change event, set the proxy accordingly
275
- // and stop polling
276
- if (proxy.is_native === false && !non_native) {
277
- proxy.is_native = true;
278
- window.clearInterval(lp._interval);
279
- lp._interval = null;
280
- }
281
- app.trigger('location-changed');
282
- });
283
- if (_has_history && !app.disable_push_state) {
284
- // bind to popstate
285
- $(window).bind('popstate.' + this.app.eventNamespace(), function(e) {
286
- app.trigger('location-changed');
287
- });
288
- // bind to link clicks that have routes
289
- $(document).delegate('a', 'click.history-' + this.app.eventNamespace(), function (e) {
290
- if (e.isDefaultPrevented() || e.metaKey || e.ctrlKey) {
291
- return;
292
- }
293
- var full_path = lp.fullPath(this);
294
- if (this.hostname == window.location.hostname &&
295
- app.lookupRoute('get', full_path) &&
296
- Sammy.targetIsThisWindow(e)) {
297
- e.preventDefault();
298
- proxy.setLocation(full_path);
299
- return false;
300
- }
301
- });
302
- }
303
- if (!lp._bindings) {
304
- lp._bindings = 0;
305
- }
306
- lp._bindings++;
307
- },
308
-
309
- // unbind the proxy events from the current app
310
- unbind: function() {
311
- $(window).unbind('hashchange.' + this.app.eventNamespace());
312
- $(window).unbind('popstate.' + this.app.eventNamespace());
313
- $(document).undelegate('a', 'click.history-' + this.app.eventNamespace());
314
- Sammy.DefaultLocationProxy._bindings--;
315
- if (Sammy.DefaultLocationProxy._bindings <= 0) {
316
- window.clearInterval(Sammy.DefaultLocationProxy._interval);
317
- Sammy.DefaultLocationProxy._interval = null;
318
- }
319
- },
320
-
321
- // get the current location from the hash.
322
- getLocation: function() {
323
- return Sammy.DefaultLocationProxy.fullPath(window.location);
324
- },
325
-
326
- // set the current location to `new_location`
327
- setLocation: function(new_location) {
328
- if (/^([^#\/]|$)/.test(new_location)) { // non-prefixed url
329
- if (_has_history && !this.app.disable_push_state) {
330
- new_location = '/' + new_location;
331
- } else {
332
- new_location = '#!/' + new_location;
333
- }
334
- }
335
- if (new_location != this.getLocation()) {
336
- // HTML5 History exists and new_location is a full path
337
- if (_has_history && !this.app.disable_push_state && /^\//.test(new_location)) {
338
- history.pushState({ path: new_location }, window.title, new_location);
339
- this.app.trigger('location-changed');
340
- } else {
341
- return (window.location = new_location);
342
- }
343
- }
344
- },
345
-
346
- _startPolling: function(every) {
347
- // set up interval
348
- var proxy = this;
349
- if (!Sammy.DefaultLocationProxy._interval) {
350
- if (!every) { every = 10; }
351
- var hashCheck = function() {
352
- var current_location = proxy.getLocation();
353
- if (typeof Sammy.DefaultLocationProxy._last_location == 'undefined' ||
354
- current_location != Sammy.DefaultLocationProxy._last_location) {
355
- window.setTimeout(function() {
356
- $(window).trigger('hashchange', [true]);
357
- }, 0);
358
- }
359
- Sammy.DefaultLocationProxy._last_location = current_location;
360
- };
361
- hashCheck();
362
- Sammy.DefaultLocationProxy._interval = window.setInterval(hashCheck, every);
363
- }
364
- }
365
- });
366
-
367
-
368
- // Sammy.Application is the Base prototype for defining 'applications'.
369
- // An 'application' is a collection of 'routes' and bound events that is
370
- // attached to an element when `run()` is called.
371
- // The only argument an 'app_function' is evaluated within the context of the application.
372
- Sammy.Application = function(app_function) {
373
- var app = this;
374
- this.routes = {};
375
- this.listeners = new Sammy.Object({});
376
- this.arounds = [];
377
- this.befores = [];
378
- // generate a unique namespace
379
- this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
380
- this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
381
- this.context_prototype.prototype = new Sammy.EventContext();
382
-
383
- if (_isFunction(app_function)) {
384
- app_function.apply(this, [this]);
385
- }
386
- // set the location proxy if not defined to the default (DefaultLocationProxy)
387
- if (!this._location_proxy) {
388
- this.setLocationProxy(new Sammy.DefaultLocationProxy(this, this.run_interval_every));
389
- }
390
- if (this.debug) {
391
- this.bindToAllEvents(function(e, data) {
392
- app.log(app.toString(), e.cleaned_type, data || {});
393
- });
394
- }
395
- };
396
-
397
- Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
398
-
399
- // the four route verbs
400
- ROUTE_VERBS: ['get','post','put','delete'],
401
-
402
- // An array of the default events triggered by the
403
- // application during its lifecycle
404
- APP_EVENTS: ['run', 'unload', 'lookup-route', 'run-route', 'route-found', 'event-context-before', 'event-context-after', 'changed', 'error', 'check-form-submission', 'redirect', 'location-changed'],
405
-
406
- _last_route: null,
407
- _location_proxy: null,
408
- _running: false,
409
-
410
- // Defines what element the application is bound to. Provide a selector
411
- // (parseable by `jQuery()`) and this will be used by `$element()`
412
- element_selector: 'body',
413
-
414
- // When set to true, logs all of the default events using `log()`
415
- debug: false,
416
-
417
- // When set to true, and the error() handler is not overridden, will actually
418
- // raise JS errors in routes (500) and when routes can't be found (404)
419
- raise_errors: false,
420
-
421
- // The time in milliseconds that the URL is queried for changes
422
- run_interval_every: 50,
423
-
424
- // if using the `DefaultLocationProxy` setting this to true will force the app to use
425
- // traditional hash based routing as opposed to the new HTML5 PushState support
426
- disable_push_state: false,
427
-
428
- // The default template engine to use when using `partial()` in an
429
- // `EventContext`. `template_engine` can either be a string that
430
- // corresponds to the name of a method/helper on EventContext or it can be a function
431
- // that takes two arguments, the content of the unrendered partial and an optional
432
- // JS object that contains interpolation data. Template engine is only called/referred
433
- // to if the extension of the partial is null or unknown. See `partial()`
434
- // for more information
435
- template_engine: null,
436
-
437
- // //=> Sammy.Application: body
438
- toString: function() {
439
- return 'Sammy.Application:' + this.element_selector;
440
- },
441
-
442
- // returns a jQuery object of the Applications bound element.
443
- $element: function(selector) {
444
- return selector ? $(this.element_selector).find(selector) : $(this.element_selector);
445
- },
446
-
447
- // `use()` is the entry point for including Sammy plugins.
448
- // The first argument to use should be a function() that is evaluated
449
- // in the context of the current application, just like the `app_function`
450
- // argument to the `Sammy.Application` constructor.
451
- //
452
- // Any additional arguments are passed to the app function sequentially.
453
- //
454
- // For much more detail about plugins, check out:
455
- // [http://sammyjs.org/docs/plugins](http://sammyjs.org/docs/plugins)
456
- //
457
- // ### Example
458
- //
459
- // var MyPlugin = function(app, prepend) {
460
- //
461
- // this.helpers({
462
- // myhelper: function(text) {
463
- // alert(prepend + " " + text);
464
- // }
465
- // });
466
- //
467
- // };
468
- //
469
- // var app = $.sammy(function() {
470
- //
471
- // this.use(MyPlugin, 'This is my plugin');
472
- //
473
- // this.get('#/', function() {
474
- // this.myhelper('and dont you forget it!');
475
- // //=> Alerts: This is my plugin and dont you forget it!
476
- // });
477
- //
478
- // });
479
- //
480
- // If plugin is passed as a string it assumes your are trying to load
481
- // Sammy."Plugin". This is the preferred way of loading core Sammy plugins
482
- // as it allows for better error-messaging.
483
- //
484
- // ### Example
485
- //
486
- // $.sammy(function() {
487
- // this.use('Mustache'); //=> Sammy.Mustache
488
- // this.use('Storage'); //=> Sammy.Storage
489
- // });
490
- //
491
- use: function() {
492
- // flatten the arguments
493
- var args = _makeArray(arguments),
494
- plugin = args.shift(),
495
- plugin_name = plugin || '';
496
- try {
497
- args.unshift(this);
498
- if (typeof plugin == 'string') {
499
- plugin_name = 'Sammy.' + plugin;
500
- plugin = Sammy[plugin];
501
- }
502
- plugin.apply(this, args);
503
- } catch(e) {
504
- if (typeof plugin === 'undefined') {
505
- this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
506
- } else if (!_isFunction(plugin)) {
507
- this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
508
- } else {
509
- this.error("Plugin Error", e);
510
- }
511
- }
512
- return this;
513
- },
514
-
515
- // Sets the location proxy for the current app. By default this is set to
516
- // a new `Sammy.DefaultLocationProxy` on initialization. However, you can set
517
- // the location_proxy inside you're app function to give your app a custom
518
- // location mechanism. See `Sammy.DefaultLocationProxy` and `Sammy.DataLocationProxy`
519
- // for examples.
520
- //
521
- // `setLocationProxy()` takes an initialized location proxy.
522
- //
523
- // ### Example
524
- //
525
- // // to bind to data instead of the default hash;
526
- // var app = $.sammy(function() {
527
- // this.setLocationProxy(new Sammy.DataLocationProxy(this));
528
- // });
529
- //
530
- setLocationProxy: function(new_proxy) {
531
- var original_proxy = this._location_proxy;
532
- this._location_proxy = new_proxy;
533
- if (this.isRunning()) {
534
- if (original_proxy) {
535
- // if there is already a location proxy, unbind it.
536
- original_proxy.unbind();
537
- }
538
- this._location_proxy.bind();
539
- }
540
- },
541
-
542
- // provide log() override for inside an app that includes the relevant application element_selector
543
- log: function() {
544
- Sammy.log.apply(Sammy, Array.prototype.concat.apply([this.element_selector],arguments));
545
- },
546
-
547
-
548
- // `route()` is the main method for defining routes within an application.
549
- // For great detail on routes, check out:
550
- // [http://sammyjs.org/docs/routes](http://sammyjs.org/docs/routes)
551
- //
552
- // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
553
- //
554
- // ### Arguments
555
- //
556
- // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
557
- // of the ROUTE_VERBS. If only two arguments are passed,
558
- // the first argument is the path, the second is the callback and the verb
559
- // is assumed to be 'any'.
560
- // * `path` A Regexp or a String representing the path to match to invoke this verb.
561
- // * `callback` A Function that is called/evaluated when the route is run see: `runRoute()`.
562
- // It is also possible to pass a string as the callback, which is looked up as the name
563
- // of a method on the application.
564
- //
565
- route: function(verb, path) {
566
- var app = this, param_names = [], add_route, path_match, callback = Array.prototype.slice.call(arguments,2);
567
-
568
- // if the method signature is just (path, callback)
569
- // assume the verb is 'any'
570
- if (callback.length === 0 && _isFunction(path)) {
571
- path = verb;
572
- callback = [path];
573
- verb = 'any';
574
- }
575
-
576
- verb = verb.toLowerCase(); // ensure verb is lower case
577
-
578
- // if path is a string turn it into a regex
579
- if (path.constructor == String) {
580
-
581
- // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
582
- // 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
583
- // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
584
- PATH_NAME_MATCHER.lastIndex = 0;
585
-
586
- // find the names
587
- while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
588
- param_names.push(path_match[1]);
589
- }
590
- // replace with the path replacement
591
- path = new RegExp(path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
592
- }
593
- // lookup callbacks
594
- $.each(callback,function(i,cb){
595
- if (typeof(cb) === 'string') {
596
- callback[i] = app[cb];
597
- }
598
- });
599
-
600
- add_route = function(with_verb) {
601
- var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
602
- // add route to routes array
603
- app.routes[with_verb] = app.routes[with_verb] || [];
604
- // place routes in order of definition
605
- app.routes[with_verb].push(r);
606
- };
607
-
608
- if (verb === 'any') {
609
- $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
610
- } else {
611
- add_route(verb);
612
- }
613
-
614
- // return the app
615
- return this;
616
- },
617
-
618
- // Alias for route('get', ...)
619
- get: _routeWrapper('get'),
620
-
621
- // Alias for route('post', ...)
622
- post: _routeWrapper('post'),
623
-
624
- // Alias for route('put', ...)
625
- put: _routeWrapper('put'),
626
-
627
- // Alias for route('delete', ...)
628
- del: _routeWrapper('delete'),
629
-
630
- // Alias for route('any', ...)
631
- any: _routeWrapper('any'),
632
-
633
- // `mapRoutes` takes an array of arrays, each array being passed to route()
634
- // as arguments, this allows for mass definition of routes. Another benefit is
635
- // this makes it possible/easier to load routes via remote JSON.
636
- //
637
- // ### Example
638
- //
639
- // var app = $.sammy(function() {
640
- //
641
- // this.mapRoutes([
642
- // ['get', '#/', function() { this.log('index'); }],
643
- // // strings in callbacks are looked up as methods on the app
644
- // ['post', '#/create', 'addUser'],
645
- // // No verb assumes 'any' as the verb
646
- // [/dowhatever/, function() { this.log(this.verb, this.path)}];
647
- // ]);
648
- // });
649
- //
650
- mapRoutes: function(route_array) {
651
- var app = this;
652
- $.each(route_array, function(i, route_args) {
653
- app.route.apply(app, route_args);
654
- });
655
- return this;
656
- },
657
-
658
- // A unique event namespace defined per application.
659
- // All events bound with `bind()` are automatically bound within this space.
660
- eventNamespace: function() {
661
- return ['sammy-app', this.namespace].join('-');
662
- },
663
-
664
- // Works just like `jQuery.fn.bind()` with a couple notable differences.
665
- //
666
- // * It binds all events to the application element
667
- // * All events are bound within the `eventNamespace()`
668
- // * Events are not actually bound until the application is started with `run()`
669
- // * callbacks are evaluated within the context of a Sammy.EventContext
670
- //
671
- bind: function(name, data, callback) {
672
- var app = this;
673
- // build the callback
674
- // if the arity is 2, callback is the second argument
675
- if (typeof callback == 'undefined') { callback = data; }
676
- var listener_callback = function() {
677
- // pull off the context from the arguments to the callback
678
- var e, context, data;
679
- e = arguments[0];
680
- data = arguments[1];
681
- if (data && data.context) {
682
- context = data.context;
683
- delete data.context;
684
- } else {
685
- context = new app.context_prototype(app, 'bind', e.type, data, e.target);
686
- }
687
- e.cleaned_type = e.type.replace(app.eventNamespace(), '');
688
- callback.apply(context, [e, data]);
689
- };
690
-
691
- // it could be that the app element doesnt exist yet
692
- // so attach to the listeners array and then run()
693
- // will actually bind the event.
694
- if (!this.listeners[name]) { this.listeners[name] = []; }
695
- this.listeners[name].push(listener_callback);
696
- if (this.isRunning()) {
697
- // if the app is running
698
- // *actually* bind the event to the app element
699
- this._listen(name, listener_callback);
700
- }
701
- return this;
702
- },
703
-
704
- // Triggers custom events defined with `bind()`
705
- //
706
- // ### Arguments
707
- //
708
- // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
709
- // * `data` An optional Object that can be passed to the bound callback.
710
- // * `context` An optional context/Object in which to execute the bound callback.
711
- // If no context is supplied a the context is a new `Sammy.EventContext`
712
- //
713
- trigger: function(name, data) {
714
- this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
715
- return this;
716
- },
717
-
718
- // Reruns the current route
719
- refresh: function() {
720
- this.last_location = null;
721
- this.trigger('location-changed');
722
- return this;
723
- },
724
-
725
- // Takes a single callback that is pushed on to a stack.
726
- // Before any route is run, the callbacks are evaluated in order within
727
- // the current `Sammy.EventContext`
728
- //
729
- // If any of the callbacks explicitly return false, execution of any
730
- // further callbacks and the route itself is halted.
731
- //
732
- // You can also provide a set of options that will define when to run this
733
- // before based on the route it proceeds.
734
- //
735
- // ### Example
736
- //
737
- // var app = $.sammy(function() {
738
- //
739
- // // will run at #/route but not at #/
740
- // this.before('#/route', function() {
741
- // //...
742
- // });
743
- //
744
- // // will run at #/ but not at #/route
745
- // this.before({except: {path: '#/route'}}, function() {
746
- // this.log('not before #/route');
747
- // });
748
- //
749
- // this.get('#/', function() {});
750
- //
751
- // this.get('#/route', function() {});
752
- //
753
- // });
754
- //
755
- // See `contextMatchesOptions()` for a full list of supported options
756
- //
757
- before: function(options, callback) {
758
- if (_isFunction(options)) {
759
- callback = options;
760
- options = {};
761
- }
762
- this.befores.push([options, callback]);
763
- return this;
764
- },
765
-
766
- // A shortcut for binding a callback to be run after a route is executed.
767
- // After callbacks have no guarunteed order.
768
- after: function(callback) {
769
- return this.bind('event-context-after', callback);
770
- },
771
-
772
-
773
- // Adds an around filter to the application. around filters are functions
774
- // that take a single argument `callback` which is the entire route
775
- // execution path wrapped up in a closure. This means you can decide whether
776
- // or not to proceed with execution by not invoking `callback` or,
777
- // more usefully wrapping callback inside the result of an asynchronous execution.
778
- //
779
- // ### Example
780
- //
781
- // The most common use case for around() is calling a _possibly_ async function
782
- // and executing the route within the functions callback:
783
- //
784
- // var app = $.sammy(function() {
785
- //
786
- // var current_user = false;
787
- //
788
- // function checkLoggedIn(callback) {
789
- // // /session returns a JSON representation of the logged in user
790
- // // or an empty object
791
- // if (!current_user) {
792
- // $.getJSON('/session', function(json) {
793
- // if (json.login) {
794
- // // show the user as logged in
795
- // current_user = json;
796
- // // execute the route path
797
- // callback();
798
- // } else {
799
- // // show the user as not logged in
800
- // current_user = false;
801
- // // the context of aroundFilters is an EventContext
802
- // this.redirect('#/login');
803
- // }
804
- // });
805
- // } else {
806
- // // execute the route path
807
- // callback();
808
- // }
809
- // };
810
- //
811
- // this.around(checkLoggedIn);
812
- //
813
- // });
814
- //
815
- around: function(callback) {
816
- this.arounds.push(callback);
817
- return this;
818
- },
819
-
820
- // Adds a onComplete function to the application. onComplete functions are executed
821
- // at the end of a chain of route callbacks, if they call next(). Unlike after,
822
- // which is called as soon as the route is complete, onComplete is like a final next()
823
- // for all routes, and is thus run asynchronously
824
- //
825
- // ### Example
826
- //
827
- // app.get('/chain',function(context,next){
828
- // console.log('chain1');
829
- // next();
830
- // },function(context,next){
831
- // console.log('chain2');
832
- // next();
833
- // });
834
- // app.get('/link',function(context,next){
835
- // console.log('link1');
836
- // next();
837
- // },function(context,next){
838
- // console.log('link2');
839
- // next();
840
- // });
841
- // app.onComplete(function(){
842
- // console.log("Running finally")
843
- // });
844
- //
845
- // If you go to '/chain', you will get the following messages:
846
- // chain1
847
- // chain2
848
- // Running onComplete
849
- //
850
- //
851
- // If you go to /link, you will get the following messages:
852
- // link1
853
- // link2
854
- // Running onComplete
855
- //
856
- // It really comes to play when doing asynchronous:
857
- // app.get('/chain',function(context,next){
858
- // $.get('/my/url',function(){
859
- // console.log('chain1');
860
- // next();
861
- // })
862
- // },function(context,next){
863
- // console.log('chain2');
864
- // next();
865
- // });
866
- //
867
- onComplete: function(callback) {
868
- this._onComplete = callback;
869
- return this;
870
- },
871
-
872
- // Returns `true` if the current application is running.
873
- isRunning: function() {
874
- return this._running;
875
- },
876
-
877
- // Helpers extends the EventContext prototype specific to this app.
878
- // This allows you to define app specific helper functions that can be used
879
- // whenever you're inside of an event context (templates, routes, bind).
880
- //
881
- // ### Example
882
- //
883
- // var app = $.sammy(function() {
884
- //
885
- // helpers({
886
- // upcase: function(text) {
887
- // return text.toString().toUpperCase();
888
- // }
889
- // });
890
- //
891
- // get('#/', function() { with(this) {
892
- // // inside of this context I can use the helpers
893
- // $('#main').html(upcase($('#main').text());
894
- // }});
895
- //
896
- // });
897
- //
898
- //
899
- // ### Arguments
900
- //
901
- // * `extensions` An object collection of functions to extend the context.
902
- //
903
- helpers: function(extensions) {
904
- $.extend(this.context_prototype.prototype, extensions);
905
- return this;
906
- },
907
-
908
- // Helper extends the event context just like `helpers()` but does it
909
- // a single method at a time. This is especially useful for dynamically named
910
- // helpers
911
- //
912
- // ### Example
913
- //
914
- // // Trivial example that adds 3 helper methods to the context dynamically
915
- // var app = $.sammy(function(app) {
916
- //
917
- // $.each([1,2,3], function(i, num) {
918
- // app.helper('helper' + num, function() {
919
- // this.log("I'm helper number " + num);
920
- // });
921
- // });
922
- //
923
- // this.get('#/', function() {
924
- // this.helper2(); //=> I'm helper number 2
925
- // });
926
- // });
927
- //
928
- // ### Arguments
929
- //
930
- // * `name` The name of the method
931
- // * `method` The function to be added to the prototype at `name`
932
- //
933
- helper: function(name, method) {
934
- this.context_prototype.prototype[name] = method;
935
- return this;
936
- },
937
-
938
- // Actually starts the application's lifecycle. `run()` should be invoked
939
- // within a document.ready block to ensure the DOM exists before binding events, etc.
940
- //
941
- // ### Example
942
- //
943
- // var app = $.sammy(function() { ... }); // your application
944
- // $(function() { // document.ready
945
- // app.run();
946
- // });
947
- //
948
- // ### Arguments
949
- //
950
- // * `start_url` Optionally, a String can be passed which the App will redirect to
951
- // after the events/routes have been bound.
952
- run: function(start_url) {
953
- if (this.isRunning()) { return false; }
954
- var app = this;
955
-
956
- // actually bind all the listeners
957
- $.each(this.listeners.toHash(), function(name, callbacks) {
958
- $.each(callbacks, function(i, listener_callback) {
959
- app._listen(name, listener_callback);
960
- });
961
- });
962
-
963
- this.trigger('run', {start_url: start_url});
964
- this._running = true;
965
- // set last location
966
- this.last_location = null;
967
- if (!(/\#(.+)/.test(this.getLocation())) && typeof start_url != 'undefined') {
968
- this.setLocation(start_url);
969
- }
970
- // check url
971
- this._checkLocation();
972
- this._location_proxy.bind();
973
- this.bind('location-changed', function() {
974
- app._checkLocation();
975
- });
976
-
977
- // bind to submit to capture post/put/delete routes
978
- this.bind('submit', function(e) {
979
- if ( !Sammy.targetIsThisWindow(e) ) { return true; }
980
- var returned = app._checkFormSubmission($(e.target).closest('form'));
981
- return (returned === false) ? e.preventDefault() : false;
982
- });
983
-
984
- // bind unload to body unload
985
- $(window).bind('unload', function() {
986
- app.unload();
987
- });
988
-
989
- // trigger html changed
990
- return this.trigger('changed');
991
- },
992
-
993
- // The opposite of `run()`, un-binds all event listeners and intervals
994
- // `run()` Automatically binds a `onunload` event to run this when
995
- // the document is closed.
996
- unload: function() {
997
- if (!this.isRunning()) { return false; }
998
- var app = this;
999
- this.trigger('unload');
1000
- // clear interval
1001
- this._location_proxy.unbind();
1002
- // unbind form submits
1003
- this.$element().unbind('submit').removeClass(app.eventNamespace());
1004
- // unbind all events
1005
- $.each(this.listeners.toHash() , function(name, listeners) {
1006
- $.each(listeners, function(i, listener_callback) {
1007
- app._unlisten(name, listener_callback);
1008
- });
1009
- });
1010
- this._running = false;
1011
- return this;
1012
- },
1013
-
1014
- // Not only runs `unbind` but also destroys the app reference.
1015
- destroy: function() {
1016
- this.unload();
1017
- delete Sammy.apps[this.element_selector];
1018
- return this;
1019
- },
1020
-
1021
- // Will bind a single callback function to every event that is already
1022
- // being listened to in the app. This includes all the `APP_EVENTS`
1023
- // as well as any custom events defined with `bind()`.
1024
- //
1025
- // Used internally for debug logging.
1026
- bindToAllEvents: function(callback) {
1027
- var app = this;
1028
- // bind to the APP_EVENTS first
1029
- $.each(this.APP_EVENTS, function(i, e) {
1030
- app.bind(e, callback);
1031
- });
1032
- // next, bind to listener names (only if they dont exist in APP_EVENTS)
1033
- $.each(this.listeners.keys(true), function(i, name) {
1034
- if ($.inArray(name, app.APP_EVENTS) == -1) {
1035
- app.bind(name, callback);
1036
- }
1037
- });
1038
- return this;
1039
- },
1040
-
1041
- // Returns a copy of the given path with any query string after the hash
1042
- // removed.
1043
- routablePath: function(path) {
1044
- return path.replace(QUERY_STRING_MATCHER, '');
1045
- },
1046
-
1047
- // Given a verb and a String path, will return either a route object or false
1048
- // if a matching route can be found within the current defined set.
1049
- lookupRoute: function(verb, path) {
1050
- var app = this, routed = false, i = 0, l, route;
1051
- if (typeof this.routes[verb] != 'undefined') {
1052
- l = this.routes[verb].length;
1053
- for (; i < l; i++) {
1054
- route = this.routes[verb][i];
1055
- if (app.routablePath(path).match(route.path)) {
1056
- routed = route;
1057
- break;
1058
- }
1059
- }
1060
- }
1061
- return routed;
1062
- },
1063
-
1064
- // First, invokes `lookupRoute()` and if a route is found, parses the
1065
- // possible URL params and then invokes the route's callback within a new
1066
- // `Sammy.EventContext`. If the route can not be found, it calls
1067
- // `notFound()`. If `raise_errors` is set to `true` and
1068
- // the `error()` has not been overridden, it will throw an actual JS
1069
- // error.
1070
- //
1071
- // You probably will never have to call this directly.
1072
- //
1073
- // ### Arguments
1074
- //
1075
- // * `verb` A String for the verb.
1076
- // * `path` A String path to lookup.
1077
- // * `params` An Object of Params pulled from the URI or passed directly.
1078
- //
1079
- // ### Returns
1080
- //
1081
- // Either returns the value returned by the route callback or raises a 404 Not Found error.
1082
- //
1083
- runRoute: function(verb, path, params, target) {
1084
- var app = this,
1085
- route = this.lookupRoute(verb, path),
1086
- context,
1087
- wrapped_route,
1088
- arounds,
1089
- around,
1090
- befores,
1091
- before,
1092
- callback_args,
1093
- path_params,
1094
- final_returned;
1095
-
1096
- if (this.debug) {
1097
- this.log('runRoute', [verb, path].join(' '));
1098
- }
1099
-
1100
- this.trigger('run-route', {verb: verb, path: path, params: params});
1101
- if (typeof params == 'undefined') { params = {}; }
1102
-
1103
- $.extend(params, this._parseQueryString(path));
1104
-
1105
- if (route) {
1106
- this.trigger('route-found', {route: route});
1107
- // pull out the params from the path
1108
- if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
1109
- // first match is the full path
1110
- path_params.shift();
1111
- // for each of the matches
1112
- $.each(path_params, function(i, param) {
1113
- // if theres a matching param name
1114
- if (route.param_names[i]) {
1115
- // set the name to the match
1116
- params[route.param_names[i]] = _decode(param);
1117
- } else {
1118
- // initialize 'splat'
1119
- if (!params.splat) { params.splat = []; }
1120
- params.splat.push(_decode(param));
1121
- }
1122
- });
1123
- }
1124
-
1125
- // set event context
1126
- context = new this.context_prototype(this, verb, path, params, target);
1127
- // ensure arrays
1128
- arounds = this.arounds.slice(0);
1129
- befores = this.befores.slice(0);
1130
- // set the callback args to the context + contents of the splat
1131
- callback_args = [context];
1132
- if (params.splat) {
1133
- callback_args = callback_args.concat(params.splat);
1134
- }
1135
- // wrap the route up with the before filters
1136
- wrapped_route = function() {
1137
- var returned, i, nextRoute;
1138
- while (befores.length > 0) {
1139
- before = befores.shift();
1140
- // check the options
1141
- if (app.contextMatchesOptions(context, before[0])) {
1142
- returned = before[1].apply(context, [context]);
1143
- if (returned === false) { return false; }
1144
- }
1145
- }
1146
- app.last_route = route;
1147
- context.trigger('event-context-before', {context: context});
1148
- // run multiple callbacks
1149
- if (typeof(route.callback) === "function") {
1150
- route.callback = [route.callback];
1151
- }
1152
- if (route.callback && route.callback.length) {
1153
- i = -1;
1154
- nextRoute = function() {
1155
- i++;
1156
- if (route.callback[i]) {
1157
- returned = route.callback[i].apply(context,callback_args);
1158
- } else if (app._onComplete && typeof(app._onComplete === "function")) {
1159
- app._onComplete(context);
1160
- }
1161
- };
1162
- callback_args.push(nextRoute);
1163
- nextRoute();
1164
- }
1165
- context.trigger('event-context-after', {context: context});
1166
- return returned;
1167
- };
1168
- $.each(arounds.reverse(), function(i, around) {
1169
- var last_wrapped_route = wrapped_route;
1170
- wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
1171
- });
1172
- try {
1173
- final_returned = wrapped_route();
1174
- } catch(e) {
1175
- this.error(['500 Error', verb, path].join(' '), e);
1176
- }
1177
- return final_returned;
1178
- } else {
1179
- return this.notFound(verb, path);
1180
- }
1181
- },
1182
-
1183
- // Matches an object of options against an `EventContext` like object that
1184
- // contains `path` and `verb` attributes. Internally Sammy uses this
1185
- // for matching `before()` filters against specific options. You can set the
1186
- // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
1187
- // those that match the options.
1188
- //
1189
- // ### Example
1190
- //
1191
- // var app = $.sammy(),
1192
- // context = {verb: 'get', path: '#/mypath'};
1193
- //
1194
- // // match against a path string
1195
- // app.contextMatchesOptions(context, '#/mypath'); //=> true
1196
- // app.contextMatchesOptions(context, '#/otherpath'); //=> false
1197
- // // equivalent to
1198
- // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
1199
- // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
1200
- // // match against a path regexp
1201
- // app.contextMatchesOptions(context, /path/); //=> true
1202
- // app.contextMatchesOptions(context, /^path/); //=> false
1203
- // // match only a verb
1204
- // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
1205
- // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
1206
- // // match all except a verb
1207
- // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
1208
- // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
1209
- // // match all except a path
1210
- // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
1211
- // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
1212
- // // match multiple paths
1213
- // app.contextMatchesOptions(context, {path: ['#/mypath', '#/otherpath']}); //=> true
1214
- // app.contextMatchesOptions(context, {path: ['#/otherpath', '#/thirdpath']}); //=> false
1215
- // // equivalent to
1216
- // app.contextMatchesOptions(context, {only: {path: ['#/mypath', '#/otherpath']}}); //=> true
1217
- // app.contextMatchesOptions(context, {only: {path: ['#/otherpath', '#/thirdpath']}}); //=> false
1218
- // // match all except multiple paths
1219
- // app.contextMatchesOptions(context, {except: {path: ['#/mypath', '#/otherpath']}}); //=> false
1220
- // app.contextMatchesOptions(context, {except: {path: ['#/otherpath', '#/thirdpath']}}); //=> true
1221
- //
1222
- contextMatchesOptions: function(context, match_options, positive) {
1223
- var options = match_options;
1224
- // normalize options
1225
- if (typeof options === 'string' || _isRegExp(options)) {
1226
- options = {path: options};
1227
- }
1228
- if (typeof positive === 'undefined') {
1229
- positive = true;
1230
- }
1231
- // empty options always match
1232
- if ($.isEmptyObject(options)) {
1233
- return true;
1234
- }
1235
- // Do we have to match against multiple paths?
1236
- if (_isArray(options.path)){
1237
- var results, numopt, opts, len;
1238
- results = [];
1239
- for (numopt = 0, len = options.path.length; numopt < len; numopt += 1) {
1240
- opts = $.extend({}, options, {path: options.path[numopt]});
1241
- results.push(this.contextMatchesOptions(context, opts));
1242
- }
1243
- var matched = $.inArray(true, results) > -1 ? true : false;
1244
- return positive ? matched : !matched;
1245
- }
1246
- if (options.only) {
1247
- return this.contextMatchesOptions(context, options.only, true);
1248
- } else if (options.except) {
1249
- return this.contextMatchesOptions(context, options.except, false);
1250
- }
1251
- var path_matched = true, verb_matched = true;
1252
- if (options.path) {
1253
- if (!_isRegExp(options.path)) {
1254
- options.path = new RegExp(options.path.toString() + '$');
1255
- }
1256
- path_matched = options.path.test(context.path);
1257
- }
1258
- if (options.verb) {
1259
- if(typeof options.verb === 'string') {
1260
- verb_matched = options.verb === context.verb;
1261
- } else {
1262
- verb_matched = options.verb.indexOf(context.verb) > -1;
1263
- }
1264
- }
1265
- return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
1266
- },
1267
-
1268
-
1269
- // Delegates to the `location_proxy` to get the current location.
1270
- // See `Sammy.DefaultLocationProxy` for more info on location proxies.
1271
- getLocation: function() {
1272
- return this._location_proxy.getLocation();
1273
- },
1274
-
1275
- // Delegates to the `location_proxy` to set the current location.
1276
- // See `Sammy.DefaultLocationProxy` for more info on location proxies.
1277
- //
1278
- // ### Arguments
1279
- //
1280
- // * `new_location` A new location string (e.g. '#/')
1281
- //
1282
- setLocation: function(new_location) {
1283
- return this._location_proxy.setLocation(new_location);
1284
- },
1285
-
1286
- // Swaps the content of `$element()` with `content`
1287
- // You can override this method to provide an alternate swap behavior
1288
- // for `EventContext.partial()`.
1289
- //
1290
- // ### Example
1291
- //
1292
- // var app = $.sammy(function() {
1293
- //
1294
- // // implements a 'fade out'/'fade in'
1295
- // this.swap = function(content, callback) {
1296
- // var context = this;
1297
- // context.$element().fadeOut('slow', function() {
1298
- // context.$element().html(content);
1299
- // context.$element().fadeIn('slow', function() {
1300
- // if (callback) {
1301
- // callback.apply();
1302
- // }
1303
- // });
1304
- // });
1305
- // };
1306
- //
1307
- // });
1308
- //
1309
- swap: function(content, callback) {
1310
- var $el = this.$element().html(content);
1311
- if (_isFunction(callback)) { callback(content); }
1312
- return $el;
1313
- },
1314
-
1315
- // a simple global cache for templates. Uses the same semantics as
1316
- // `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
1317
- // a persistent storage that lasts beyond the current request.
1318
- templateCache: function(key, value) {
1319
- if (typeof value != 'undefined') {
1320
- return _template_cache[key] = value;
1321
- } else {
1322
- return _template_cache[key];
1323
- }
1324
- },
1325
-
1326
- // clear the templateCache
1327
- clearTemplateCache: function() {
1328
- return (_template_cache = {});
1329
- },
1330
-
1331
- // This throws a '404 Not Found' error by invoking `error()`.
1332
- // Override this method or `error()` to provide custom
1333
- // 404 behavior (i.e redirecting to / or showing a warning)
1334
- notFound: function(verb, path) {
1335
- var ret = this.error(['404 Not Found', verb, path].join(' '));
1336
- return (verb === 'get') ? ret : true;
1337
- },
1338
-
1339
- // The base error handler takes a string `message` and an `Error`
1340
- // object. If `raise_errors` is set to `true` on the app level,
1341
- // this will re-throw the error to the browser. Otherwise it will send the error
1342
- // to `log()`. Override this method to provide custom error handling
1343
- // e.g logging to a server side component or displaying some feedback to the
1344
- // user.
1345
- error: function(message, original_error) {
1346
- if (!original_error) { original_error = new Error(); }
1347
- original_error.message = [message, original_error.message].join(' ');
1348
- this.trigger('error', {message: original_error.message, error: original_error});
1349
- if (this.raise_errors) {
1350
- throw(original_error);
1351
- } else {
1352
- this.log(original_error.message, original_error);
1353
- }
1354
- },
1355
-
1356
- _checkLocation: function() {
1357
- var location, returned;
1358
- // get current location
1359
- location = this.getLocation();
1360
- // compare to see if hash has changed
1361
- if (!this.last_location || this.last_location[0] != 'get' || this.last_location[1] != location) {
1362
- // reset last location
1363
- this.last_location = ['get', location];
1364
- // lookup route for current hash
1365
- returned = this.runRoute('get', location);
1366
- }
1367
- return returned;
1368
- },
1369
-
1370
- _getFormVerb: function(form) {
1371
- var $form = $(form), verb, $_method;
1372
- $_method = $form.find('input[name="_method"]');
1373
- if ($_method.length > 0) { verb = $_method.val(); }
1374
- if (!verb) { verb = $form[0].getAttribute('method'); }
1375
- if (!verb || verb === '') { verb = 'get'; }
1376
- return $.trim(verb.toString().toLowerCase());
1377
- },
1378
-
1379
- _checkFormSubmission: function(form) {
1380
- var $form, path, verb, params, returned;
1381
- this.trigger('check-form-submission', {form: form});
1382
- $form = $(form);
1383
- path = $form.attr('action') || '';
1384
- verb = this._getFormVerb($form);
1385
-
1386
- if (this.debug) {
1387
- this.log('_checkFormSubmission', $form, path, verb);
1388
- }
1389
-
1390
- if (verb === 'get') {
1391
- params = this._serializeFormParams($form);
1392
- if (params !== '') { path += '?' + params; }
1393
- this.setLocation(path);
1394
- returned = false;
1395
- } else {
1396
- params = $.extend({}, this._parseFormParams($form));
1397
- returned = this.runRoute(verb, path, params, form.get(0));
1398
- }
1399
- return (typeof returned == 'undefined') ? false : returned;
1400
- },
1401
-
1402
- _serializeFormParams: function($form) {
1403
- var queryString = "",
1404
- fields = $form.serializeArray(),
1405
- i;
1406
- if (fields.length > 0) {
1407
- queryString = this._encodeFormPair(fields[0].name, fields[0].value);
1408
- for (i = 1; i < fields.length; i++) {
1409
- queryString = queryString + "&" + this._encodeFormPair(fields[i].name, fields[i].value);
1410
- }
1411
- }
1412
- return queryString;
1413
- },
1414
-
1415
- _encodeFormPair: function(name, value){
1416
- return _encode(name) + "=" + _encode(value);
1417
- },
1418
-
1419
- _parseFormParams: function($form) {
1420
- var params = {},
1421
- form_fields = $form.serializeArray(),
1422
- i;
1423
- for (i = 0; i < form_fields.length; i++) {
1424
- params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
1425
- }
1426
- return params;
1427
- },
1428
-
1429
- _parseQueryString: function(path) {
1430
- var params = {}, parts, pairs, pair, i;
1431
-
1432
- parts = path.match(QUERY_STRING_MATCHER);
1433
- if (parts && parts[1]) {
1434
- pairs = parts[1].split('&');
1435
- for (i = 0; i < pairs.length; i++) {
1436
- pair = pairs[i].split('=');
1437
- params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1] || ""));
1438
- }
1439
- }
1440
- return params;
1441
- },
1442
-
1443
- _parseParamPair: function(params, key, value) {
1444
- if (typeof params[key] !== 'undefined') {
1445
- if (_isArray(params[key])) {
1446
- params[key].push(value);
1447
- } else {
1448
- params[key] = [params[key], value];
1449
- }
1450
- } else {
1451
- params[key] = value;
1452
- }
1453
- return params;
1454
- },
1455
-
1456
- _listen: function(name, callback) {
1457
- return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
1458
- },
1459
-
1460
- _unlisten: function(name, callback) {
1461
- return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
1462
- }
1463
-
1464
- });
1465
-
1466
- // `Sammy.RenderContext` is an object that makes sequential template loading,
1467
- // rendering and interpolation seamless even when dealing with asynchronous
1468
- // operations.
1469
- //
1470
- // `RenderContext` objects are not usually created directly, rather they are
1471
- // instantiated from an `Sammy.EventContext` by using `render()`, `load()` or
1472
- // `partial()` which all return `RenderContext` objects.
1473
- //
1474
- // `RenderContext` methods always returns a modified `RenderContext`
1475
- // for chaining (like jQuery itself).
1476
- //
1477
- // The core magic is in the `then()` method which puts the callback passed as
1478
- // an argument into a queue to be executed once the previous callback is complete.
1479
- // All the methods of `RenderContext` are wrapped in `then()` which allows you
1480
- // to queue up methods by chaining, but maintaining a guaranteed execution order
1481
- // even with remote calls to fetch templates.
1482
- //
1483
- Sammy.RenderContext = function(event_context) {
1484
- this.event_context = event_context;
1485
- this.callbacks = [];
1486
- this.previous_content = null;
1487
- this.content = null;
1488
- this.next_engine = false;
1489
- this.waiting = false;
1490
- };
1491
-
1492
- Sammy.RenderContext.prototype = $.extend({}, Sammy.Object.prototype, {
1493
-
1494
- // The "core" of the `RenderContext` object, adds the `callback` to the
1495
- // queue. If the context is `waiting` (meaning an async operation is happening)
1496
- // then the callback will be executed in order, once the other operations are
1497
- // complete. If there is no currently executing operation, the `callback`
1498
- // is executed immediately.
1499
- //
1500
- // The value returned from the callback is stored in `content` for the
1501
- // subsequent operation. If you return `false`, the queue will pause, and
1502
- // the next callback in the queue will not be executed until `next()` is
1503
- // called. This allows for the guaranteed order of execution while working
1504
- // with async operations.
1505
- //
1506
- // If then() is passed a string instead of a function, the string is looked
1507
- // up as a helper method on the event context.
1508
- //
1509
- // ### Example
1510
- //
1511
- // this.get('#/', function() {
1512
- // // initialize the RenderContext
1513
- // // Even though `load()` executes async, the next `then()`
1514
- // // wont execute until the load finishes
1515
- // this.load('myfile.txt')
1516
- // .then(function(content) {
1517
- // // the first argument to then is the content of the
1518
- // // prev operation
1519
- // $('#main').html(content);
1520
- // });
1521
- // });
1522
- //
1523
- then: function(callback) {
1524
- if (!_isFunction(callback)) {
1525
- // if a string is passed to then, assume we want to call
1526
- // a helper on the event context in its context
1527
- if (typeof callback === 'string' && callback in this.event_context) {
1528
- var helper = this.event_context[callback];
1529
- callback = function(content) {
1530
- return helper.apply(this.event_context, [content]);
1531
- };
1532
- } else {
1533
- return this;
1534
- }
1535
- }
1536
- var context = this;
1537
- if (this.waiting) {
1538
- this.callbacks.push(callback);
1539
- } else {
1540
- this.wait();
1541
- window.setTimeout(function() {
1542
- var returned = callback.apply(context, [context.content, context.previous_content]);
1543
- if (returned !== false) {
1544
- context.next(returned);
1545
- }
1546
- }, 0);
1547
- }
1548
- return this;
1549
- },
1550
-
1551
- // Pause the `RenderContext` queue. Combined with `next()` allows for async
1552
- // operations.
1553
- //
1554
- // ### Example
1555
- //
1556
- // this.get('#/', function() {
1557
- // this.load('mytext.json')
1558
- // .then(function(content) {
1559
- // var context = this,
1560
- // data = JSON.parse(content);
1561
- // // pause execution
1562
- // context.wait();
1563
- // // post to a url
1564
- // $.post(data.url, {}, function(response) {
1565
- // context.next(JSON.parse(response));
1566
- // });
1567
- // })
1568
- // .then(function(data) {
1569
- // // data is json from the previous post
1570
- // $('#message').text(data.status);
1571
- // });
1572
- // });
1573
- wait: function() {
1574
- this.waiting = true;
1575
- },
1576
-
1577
- // Resume the queue, setting `content` to be used in the next operation.
1578
- // See `wait()` for an example.
1579
- next: function(content) {
1580
- this.waiting = false;
1581
- if (typeof content !== 'undefined') {
1582
- this.previous_content = this.content;
1583
- this.content = content;
1584
- }
1585
- if (this.callbacks.length > 0) {
1586
- this.then(this.callbacks.shift());
1587
- }
1588
- },
1589
-
1590
- // Load a template into the context.
1591
- // The `location` can either be a string specifying the remote path to the
1592
- // file, a jQuery object, or a DOM element.
1593
- //
1594
- // No interpolation happens by default, the content is stored in
1595
- // `content`.
1596
- //
1597
- // In the case of a path, unless the option `{cache: false}` is passed the
1598
- // data is stored in the app's `templateCache()`.
1599
- //
1600
- // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
1601
- // This is useful for nesting templates as part of the initial page load wrapped
1602
- // in invisible elements or `<script>` tags. With template paths, the template
1603
- // engine is looked up by the extension. For DOM/jQuery embedded templates,
1604
- // this isnt possible, so there are a couple of options:
1605
- //
1606
- // * pass an `{engine:}` option.
1607
- // * define the engine in the `data-engine` attribute of the passed node.
1608
- // * just store the raw template data and use `interpolate()` manually
1609
- //
1610
- // If a `callback` is passed it is executed after the template load.
1611
- load: function(location, options, callback) {
1612
- var context = this;
1613
- return this.then(function() {
1614
- var should_cache, cached, is_json, location_array;
1615
- if (_isFunction(options)) {
1616
- callback = options;
1617
- options = {};
1618
- } else {
1619
- options = $.extend({}, options);
1620
- }
1621
- if (callback) { this.then(callback); }
1622
- if (typeof location === 'string') {
1623
- // it's a path
1624
- is_json = (location.match(/\.json$/) || options.json);
1625
- should_cache = is_json ? options.cache === true : options.cache !== false;
1626
- context.next_engine = context.event_context.engineFor(location);
1627
- delete options.cache;
1628
- delete options.json;
1629
- if (options.engine) {
1630
- context.next_engine = options.engine;
1631
- delete options.engine;
1632
- }
1633
- if (should_cache && (cached = this.event_context.app.templateCache(location))) {
1634
- return cached;
1635
- }
1636
- this.wait();
1637
- $.ajax($.extend({
1638
- url: location,
1639
- data: {},
1640
- dataType: is_json ? 'json' : 'text',
1641
- type: 'get',
1642
- success: function(data) {
1643
- if (should_cache) {
1644
- context.event_context.app.templateCache(location, data);
1645
- }
1646
- context.next(data);
1647
- }
1648
- }, options));
1649
- return false;
1650
- } else {
1651
- // it's a dom/jQuery
1652
- if (location.nodeType) {
1653
- return location.innerHTML;
1654
- }
1655
- if (location.selector) {
1656
- // it's a jQuery
1657
- context.next_engine = location.attr('data-engine');
1658
- if (options.clone === false) {
1659
- return location.remove()[0].innerHTML.toString();
1660
- } else {
1661
- return location[0].innerHTML.toString();
1662
- }
1663
- }
1664
- }
1665
- });
1666
- },
1667
-
1668
- // Load partials
1669
- //
1670
- // ### Example
1671
- //
1672
- // this.loadPartials({mypartial: '/path/to/partial'});
1673
- //
1674
- loadPartials: function(partials) {
1675
- var name;
1676
- if(partials) {
1677
- this.partials = this.partials || {};
1678
- for(name in partials) {
1679
- (function(context, name) {
1680
- context.load(partials[name])
1681
- .then(function(template) {
1682
- this.partials[name] = template;
1683
- });
1684
- })(this, name);
1685
- }
1686
- }
1687
- return this;
1688
- },
1689
-
1690
- // `load()` a template and then `interpolate()` it with data.
1691
- //
1692
- // can be called with multiple different signatures:
1693
- //
1694
- // this.render(callback);
1695
- // this.render('/location');
1696
- // this.render('/location', {some: data});
1697
- // this.render('/location', callback);
1698
- // this.render('/location', {some: data}, callback);
1699
- // this.render('/location', {some: data}, {my: partials});
1700
- // this.render('/location', callback, {my: partials});
1701
- // this.render('/location', {some: data}, callback, {my: partials});
1702
- //
1703
- // ### Example
1704
- //
1705
- // this.get('#/', function() {
1706
- // this.render('mytemplate.template', {name: 'test'});
1707
- // });
1708
- //
1709
- render: function(location, data, callback, partials) {
1710
- if (_isFunction(location) && !data) {
1711
- // invoked as render(callback)
1712
- return this.then(location);
1713
- } else {
1714
- if(_isFunction(data)) {
1715
- // invoked as render(location, callback, [partials])
1716
- partials = callback;
1717
- callback = data;
1718
- data = null;
1719
- } else if(callback && !_isFunction(callback)) {
1720
- // invoked as render(location, data, partials)
1721
- partials = callback;
1722
- callback = null;
1723
- }
1724
-
1725
- return this.loadPartials(partials)
1726
- .load(location)
1727
- .interpolate(data, location)
1728
- .then(callback);
1729
- }
1730
- },
1731
-
1732
- // `render()` the `location` with `data` and then `swap()` the
1733
- // app's `$element` with the rendered content.
1734
- partial: function(location, data, callback, partials) {
1735
- if (_isFunction(callback)) {
1736
- // invoked as partial(location, data, callback, [partials])
1737
- return this.render(location, data, partials).swap(callback);
1738
- } else if (_isFunction(data)) {
1739
- // invoked as partial(location, callback, [partials])
1740
- return this.render(location, {}, callback).swap(data);
1741
- } else {
1742
- // invoked as partial(location, data, [partials])
1743
- return this.render(location, data, callback).swap();
1744
- }
1745
- },
1746
-
1747
- // defers the call of function to occur in order of the render queue.
1748
- // The function can accept any number of arguments as long as the last
1749
- // argument is a callback function. This is useful for putting arbitrary
1750
- // asynchronous functions into the queue. The content passed to the
1751
- // callback is passed as `content` to the next item in the queue.
1752
- //
1753
- // ### Example
1754
- //
1755
- // this.send($.getJSON, '/app.json')
1756
- // .then(function(json) {
1757
- // $('#message).text(json['message']);
1758
- // });
1759
- //
1760
- //
1761
- send: function() {
1762
- var context = this,
1763
- args = _makeArray(arguments),
1764
- fun = args.shift();
1765
-
1766
- if (_isArray(args[0])) { args = args[0]; }
1767
-
1768
- return this.then(function(content) {
1769
- args.push(function(response) { context.next(response); });
1770
- context.wait();
1771
- fun.apply(fun, args);
1772
- return false;
1773
- });
1774
- },
1775
-
1776
- // iterates over an array, applying the callback for each item item. the
1777
- // callback takes the same style of arguments as `jQuery.each()` (index, item).
1778
- // The return value of each callback is collected as a single string and stored
1779
- // as `content` to be used in the next iteration of the `RenderContext`.
1780
- collect: function(array, callback, now) {
1781
- var context = this;
1782
- var coll = function() {
1783
- if (_isFunction(array)) {
1784
- callback = array;
1785
- array = this.content;
1786
- }
1787
- var contents = [], doms = false;
1788
- $.each(array, function(i, item) {
1789
- var returned = callback.apply(context, [i, item]);
1790
- if (returned.jquery && returned.length == 1) {
1791
- returned = returned[0];
1792
- doms = true;
1793
- }
1794
- contents.push(returned);
1795
- return returned;
1796
- });
1797
- return doms ? contents : contents.join('');
1798
- };
1799
- return now ? coll() : this.then(coll);
1800
- },
1801
-
1802
- // loads a template, and then interpolates it for each item in the `data`
1803
- // array. If a callback is passed, it will call the callback with each
1804
- // item in the array _after_ interpolation
1805
- renderEach: function(location, name, data, callback) {
1806
- if (_isArray(name)) {
1807
- callback = data;
1808
- data = name;
1809
- name = null;
1810
- }
1811
- return this.load(location).then(function(content) {
1812
- var rctx = this;
1813
- if (!data) {
1814
- data = _isArray(this.previous_content) ? this.previous_content : [];
1815
- }
1816
- if (callback) {
1817
- $.each(data, function(i, value) {
1818
- var idata = {}, engine = this.next_engine || location;
1819
- if (name) {
1820
- idata[name] = value;
1821
- } else {
1822
- idata = value;
1823
- }
1824
- callback(value, rctx.event_context.interpolate(content, idata, engine));
1825
- });
1826
- } else {
1827
- return this.collect(data, function(i, value) {
1828
- var idata = {}, engine = this.next_engine || location;
1829
- if (name) {
1830
- idata[name] = value;
1831
- } else {
1832
- idata = value;
1833
- }
1834
- return this.event_context.interpolate(content, idata, engine);
1835
- }, true);
1836
- }
1837
- });
1838
- },
1839
-
1840
- // uses the previous loaded `content` and the `data` object to interpolate
1841
- // a template. `engine` defines the templating/interpolation method/engine
1842
- // that should be used. If `engine` is not passed, the `next_engine` is
1843
- // used. If `retain` is `true`, the final interpolated data is appended to
1844
- // the `previous_content` instead of just replacing it.
1845
- interpolate: function(data, engine, retain) {
1846
- var context = this;
1847
- return this.then(function(content, prev) {
1848
- if (!data && prev) { data = prev; }
1849
- if (this.next_engine) {
1850
- engine = this.next_engine;
1851
- this.next_engine = false;
1852
- }
1853
- var rendered = context.event_context.interpolate(content, data, engine, this.partials);
1854
- return retain ? prev + rendered : rendered;
1855
- });
1856
- },
1857
-
1858
- // Swap the return contents ensuring order. See `Application#swap`
1859
- swap: function(callback) {
1860
- return this.then(function(content) {
1861
- this.event_context.swap(content, callback);
1862
- return content;
1863
- }).trigger('changed', {});
1864
- },
1865
-
1866
- // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
1867
- appendTo: function(selector) {
1868
- return this.then(function(content) {
1869
- $(selector).append(content);
1870
- }).trigger('changed', {});
1871
- },
1872
-
1873
- // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
1874
- prependTo: function(selector) {
1875
- return this.then(function(content) {
1876
- $(selector).prepend(content);
1877
- }).trigger('changed', {});
1878
- },
1879
-
1880
- // Replaces the `$(selector)` using `html()` with the previously loaded
1881
- // `content`
1882
- replace: function(selector) {
1883
- return this.then(function(content) {
1884
- $(selector).html(content);
1885
- }).trigger('changed', {});
1886
- },
1887
-
1888
- // trigger the event in the order of the event context. Same semantics
1889
- // as `Sammy.EventContext#trigger()`. If data is omitted, `content`
1890
- // is sent as `{content: content}`
1891
- trigger: function(name, data) {
1892
- return this.then(function(content) {
1893
- if (typeof data == 'undefined') { data = {content: content}; }
1894
- this.event_context.trigger(name, data);
1895
- return content;
1896
- });
1897
- }
1898
-
1899
- });
1900
-
1901
- // `Sammy.EventContext` objects are created every time a route is run or a
1902
- // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
1903
- // This within these callbacks the special methods of `EventContext` are available.
1904
- //
1905
- // ### Example
1906
- //
1907
- // $.sammy(function() {
1908
- // // The context here is this Sammy.Application
1909
- // this.get('#/:name', function() {
1910
- // // The context here is a new Sammy.EventContext
1911
- // if (this.params['name'] == 'sammy') {
1912
- // this.partial('name.html.erb', {name: 'Sammy'});
1913
- // } else {
1914
- // this.redirect('#/somewhere-else')
1915
- // }
1916
- // });
1917
- // });
1918
- //
1919
- // Initialize a new EventContext
1920
- //
1921
- // ### Arguments
1922
- //
1923
- // * `app` The `Sammy.Application` this event is called within.
1924
- // * `verb` The verb invoked to run this context/route.
1925
- // * `path` The string path invoked to run this context/route.
1926
- // * `params` An Object of optional params to pass to the context. Is converted
1927
- // to a `Sammy.Object`.
1928
- // * `target` a DOM element that the event that holds this context originates
1929
- // from. For post, put and del routes, this is the form element that triggered
1930
- // the route.
1931
- //
1932
- Sammy.EventContext = function(app, verb, path, params, target) {
1933
- this.app = app;
1934
- this.verb = verb;
1935
- this.path = path;
1936
- this.params = new Sammy.Object(params);
1937
- this.target = target;
1938
- };
1939
-
1940
- Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
1941
-
1942
- // A shortcut to the app's `$element()`
1943
- $element: function() {
1944
- return this.app.$element(_makeArray(arguments).shift());
1945
- },
1946
-
1947
- // Look up a templating engine within the current app and context.
1948
- // `engine` can be one of the following:
1949
- //
1950
- // * a function: should conform to `function(content, data) { return interpolated; }`
1951
- // * a template path: 'template.ejs', looks up the extension to match to
1952
- // the `ejs()` helper
1953
- // * a string referring to the helper: "mustache" => `mustache()`
1954
- //
1955
- // If no engine is found, use the app's default `template_engine`
1956
- //
1957
- engineFor: function(engine) {
1958
- var context = this, engine_match;
1959
- // if path is actually an engine function just return it
1960
- if (_isFunction(engine)) { return engine; }
1961
- // lookup engine name by path extension
1962
- engine = (engine || context.app.template_engine).toString();
1963
- if ((engine_match = engine.match(/\.([^\.\?\#]+)$/))) {
1964
- engine = engine_match[1];
1965
- }
1966
- // set the engine to the default template engine if no match is found
1967
- if (engine && _isFunction(context[engine])) {
1968
- return context[engine];
1969
- }
1970
-
1971
- if (context.app.template_engine) {
1972
- return this.engineFor(context.app.template_engine);
1973
- }
1974
- return function(content, data) { return content; };
1975
- },
1976
-
1977
- // using the template `engine` found with `engineFor()`, interpolate the
1978
- // `data` into `content`
1979
- interpolate: function(content, data, engine, partials) {
1980
- return this.engineFor(engine).apply(this, [content, data, partials]);
1981
- },
1982
-
1983
- // Create and return a `Sammy.RenderContext` calling `render()` on it.
1984
- // Loads the template and interpolate the data, however does not actual
1985
- // place it in the DOM.
1986
- //
1987
- // ### Example
1988
- //
1989
- // // mytemplate.mustache <div class="name">{{name}}</div>
1990
- // render('mytemplate.mustache', {name: 'quirkey'});
1991
- // // sets the `content` to <div class="name">quirkey</div>
1992
- // render('mytemplate.mustache', {name: 'quirkey'})
1993
- // .appendTo('ul');
1994
- // // appends the rendered content to $('ul')
1995
- //
1996
- render: function(location, data, callback, partials) {
1997
- return new Sammy.RenderContext(this).render(location, data, callback, partials);
1998
- },
1999
-
2000
- // Create and return a `Sammy.RenderContext` calling `renderEach()` on it.
2001
- // Loads the template and interpolates the data for each item,
2002
- // however does not actual place it in the DOM.
2003
- //
2004
- // ### Example
2005
- //
2006
- // // mytemplate.mustache <div class="name">{{name}}</div>
2007
- // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}])
2008
- // // sets the `content` to <div class="name">quirkey</div><div class="name">endor</div>
2009
- // renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}]).appendTo('ul');
2010
- // // appends the rendered content to $('ul')
2011
- //
2012
- renderEach: function(location, name, data, callback) {
2013
- return new Sammy.RenderContext(this).renderEach(location, name, data, callback);
2014
- },
2015
-
2016
- // create a new `Sammy.RenderContext` calling `load()` with `location` and
2017
- // `options`. Called without interpolation or placement, this allows for
2018
- // preloading/caching the templates.
2019
- load: function(location, options, callback) {
2020
- return new Sammy.RenderContext(this).load(location, options, callback);
2021
- },
2022
-
2023
- // create a new `Sammy.RenderContext` calling `loadPartials()` with `partials`.
2024
- loadPartials: function(partials) {
2025
- return new Sammy.RenderContext(this).loadPartials(partials);
2026
- },
2027
-
2028
- // `render()` the `location` with `data` and then `swap()` the
2029
- // app's `$element` with the rendered content.
2030
- partial: function(location, data, callback, partials) {
2031
- return new Sammy.RenderContext(this).partial(location, data, callback, partials);
2032
- },
2033
-
2034
- // create a new `Sammy.RenderContext` calling `send()` with an arbitrary
2035
- // function
2036
- send: function() {
2037
- var rctx = new Sammy.RenderContext(this);
2038
- return rctx.send.apply(rctx, arguments);
2039
- },
2040
-
2041
- // Changes the location of the current window. If `to` begins with
2042
- // '#' it only changes the document's hash. If passed more than 1 argument
2043
- // redirect will join them together with forward slashes.
2044
- //
2045
- // ### Example
2046
- //
2047
- // redirect('#/other/route');
2048
- // // equivalent to
2049
- // redirect('#', 'other', 'route');
2050
- //
2051
- redirect: function() {
2052
- var to, args = _makeArray(arguments),
2053
- current_location = this.app.getLocation(),
2054
- l = args.length;
2055
- if (l > 1) {
2056
- var i = 0, paths = [], pairs = [], params = {}, has_params = false;
2057
- for (; i < l; i++) {
2058
- if (typeof args[i] == 'string') {
2059
- paths.push(args[i]);
2060
- } else {
2061
- $.extend(params, args[i]);
2062
- has_params = true;
2063
- }
2064
- }
2065
- to = paths.join('/');
2066
- if (has_params) {
2067
- for (var k in params) {
2068
- pairs.push(this.app._encodeFormPair(k, params[k]));
2069
- }
2070
- to += '?' + pairs.join('&');
2071
- }
2072
- } else {
2073
- to = args[0];
2074
- }
2075
- this.trigger('redirect', {to: to});
2076
- this.app.last_location = [this.verb, this.path];
2077
- this.app.setLocation(to);
2078
- if (new RegExp(to).test(current_location)) {
2079
- this.app.trigger('location-changed');
2080
- }
2081
- },
2082
-
2083
- // Triggers events on `app` within the current context.
2084
- trigger: function(name, data) {
2085
- if (typeof data == 'undefined') { data = {}; }
2086
- if (!data.context) { data.context = this; }
2087
- return this.app.trigger(name, data);
2088
- },
2089
-
2090
- // A shortcut to app's `eventNamespace()`
2091
- eventNamespace: function() {
2092
- return this.app.eventNamespace();
2093
- },
2094
-
2095
- // A shortcut to app's `swap()`
2096
- swap: function(contents, callback) {
2097
- return this.app.swap(contents, callback);
2098
- },
2099
-
2100
- // Raises a possible `notFound()` error for the current path.
2101
- notFound: function() {
2102
- return this.app.notFound(this.verb, this.path);
2103
- },
2104
-
2105
- // Default JSON parsing uses jQuery's `parseJSON()`. Include `Sammy.JSON`
2106
- // plugin for the more conformant "crockford special".
2107
- json: function(string) {
2108
- return $.parseJSON(string);
2109
- },
2110
-
2111
- // //=> Sammy.EventContext: get #/ {}
2112
- toString: function() {
2113
- return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
2114
- }
2115
-
2116
- });
2117
-
2118
- return Sammy;
2119
- });
2120
- })(jQuery, window);
8
+ (function(e,t){(function(n){typeof define=="function"&&define.amd?define(["jquery"],n):e.sammy=t.Sammy=n(e)})(function(e){var n,r="([^/]+)",i=/:([\w\d]+)/g,s=/\?([^#]*)?$/,o=function(e){return Array.prototype.slice.call(e)},u=function(e){return Object.prototype.toString.call(e)==="[object Function]"},a=function(e){return Object.prototype.toString.call(e)==="[object Array]"},f=function(e){return Object.prototype.toString.call(e)==="[object RegExp]"},l=function(e){return decodeURIComponent((e||"").replace(/\+/g," "))},c=encodeURIComponent,h=function(e){return String(e).replace(/&(?!\w+;)/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")},p=function(e){return function(){return this.route.apply(this,[e].concat(Array.prototype.slice.call(arguments)))}},d={},v=!!t.history&&!!history.pushState,m=[];return n=function(){var t=o(arguments),r,i;n.apps=n.apps||{};if(t.length===0||t[0]&&u(t[0]))return n.apply(n,["body"].concat(t));if(typeof (i=t.shift())=="string")return r=n.apps[i]||new n.Application,r.element_selector=i,t.length>0&&e.each(t,function(e,t){r.use(t)}),r.element_selector!=i&&delete n.apps[i],n.apps[r.element_selector]=r,r},n.VERSION="0.7.4",n.addLogger=function(e){m.push(e)},n.log=function(){var t=o(arguments);t.unshift("["+Date()+"]"),e.each(m,function(e,r){r.apply(n,t)})},typeof t.console!="undefined"?u(t.console.log.apply)?n.addLogger(function(){t.console.log.apply(t.console,arguments)}):n.addLogger(function(){t.console.log(arguments)}):typeof console!="undefined"&&n.addLogger(function(){console.log.apply(console,arguments)}),e.extend(n,{makeArray:o,isFunction:u,isArray:a}),n.Object=function(t){return e.extend(this,t||{})},e.extend(n.Object.prototype,{escapeHTML:h,h:h,toHash:function(){var t={};return e.each(this,function(e,n){u(n)||(t[e]=n)}),t},toHTML:function(){var t="";return e.each(this,function(e,n){u(n)||(t+="<strong>"+e+"</strong> "+n+"<br />")}),t},keys:function(e){var t=[];for(var n in this)(!u(this[n])||!e)&&t.push(n);return t},has:function(t){return this[t]&&e.trim(this[t].toString())!==""},join:function(){var e=o(arguments),t=e.shift();return e.join(t)},log:function(){n.log.apply(n,arguments)},toString:function(t){var n=[];return e.each(this,function(e,r){(!u(r)||t)&&n.push('"'+e+'": '+r.toString())}),"Sammy.Object: {"+n.join(",")+"}"}}),n.targetIsThisWindow=function(r){var i=e(r.target).attr("target");return!i||i===t.name||i==="_self"?!0:i==="_blank"?!1:i==="top"&&t===t.top?!0:!1},n.DefaultLocationProxy=function(e,t){this.app=e,this.is_native=!1,this.has_history=v,this._startPolling(t)},n.DefaultLocationProxy.fullPath=function(e){var t=e.toString().match(/^[^#]*(#.+)$/),n=t?t[1]:"";return[e.pathname,e.search,n].join("")},e.extend(n.DefaultLocationProxy.prototype,{bind:function(){var r=this,i=this.app,s=n.DefaultLocationProxy;e(t).bind("hashchange."+this.app.eventNamespace(),function(e,n){r.is_native===!1&&!n&&(r.is_native=!0,t.clearInterval(s._interval),s._interval=null),i.trigger("location-changed")}),v&&!i.disable_push_state&&(e(t).bind("popstate."+this.app.eventNamespace(),function(e){i.trigger("location-changed")}),e(document).delegate("a","click.history-"+this.app.eventNamespace(),function(e){if(e.isDefaultPrevented()||e.metaKey||e.ctrlKey)return;var o=s.fullPath(this);if(this.hostname==t.location.hostname&&i.lookupRoute("get",o)&&n.targetIsThisWindow(e))return e.preventDefault(),r.setLocation(o),!1})),s._bindings||(s._bindings=0),s._bindings++},unbind:function(){e(t).unbind("hashchange."+this.app.eventNamespace()),e(t).unbind("popstate."+this.app.eventNamespace()),e(document).undelegate("a","click.history-"+this.app.eventNamespace()),n.DefaultLocationProxy._bindings--,n.DefaultLocationProxy._bindings<=0&&(t.clearInterval(n.DefaultLocationProxy._interval),n.DefaultLocationProxy._interval=null)},getLocation:function(){return n.DefaultLocationProxy.fullPath(t.location)},setLocation:function(e){/^([^#\/]|$)/.test(e)&&(v&&!this.app.disable_push_state?e="/"+e:e="#!/"+e);if(e!=this.getLocation()){if(!(v&&!this.app.disable_push_state&&/^\//.test(e)))return t.location=e;history.pushState({path:e},t.title,e),this.app.trigger("location-changed")}},_startPolling:function(r){var i=this;if(!n.DefaultLocationProxy._interval){r||(r=10);var s=function(){var r=i.getLocation();(typeof n.DefaultLocationProxy._last_location=="undefined"||r!=n.DefaultLocationProxy._last_location)&&t.setTimeout(function(){e(t).trigger("hashchange",[!0])},0),n.DefaultLocationProxy._last_location=r};s(),n.DefaultLocationProxy._interval=t.setInterval(s,r)}}}),n.Application=function(e){var t=this;this.routes={},this.listeners=new n.Object({}),this.arounds=[],this.befores=[],this.namespace=(new Date).getTime()+"-"+parseInt(Math.random()*1e3,10),this.context_prototype=function(){n.EventContext.apply(this,arguments)},this.context_prototype.prototype=new n.EventContext,u(e)&&e.apply(this,[this]),this._location_proxy||this.setLocationProxy(new n.DefaultLocationProxy(this,this.run_interval_every)),this.debug&&this.bindToAllEvents(function(e,n){t.log(t.toString(),e.cleaned_type,n||{})})},n.Application.prototype=e.extend({},n.Object.prototype,{ROUTE_VERBS:["get","post","put","delete"],APP_EVENTS:["run","unload","lookup-route","run-route","route-found","event-context-before","event-context-after","changed","error","check-form-submission","redirect","location-changed"],_last_route:null,_location_proxy:null,_running:!1,element_selector:"body",debug:!1,raise_errors:!1,run_interval_every:50,disable_push_state:!1,template_engine:null,toString:function(){return"Sammy.Application:"+this.element_selector},$element:function(t){return t?e(this.element_selector).find(t):e(this.element_selector)},use:function(){var e=o(arguments),t=e.shift(),r=t||"";try{e.unshift(this),typeof t=="string"&&(r="Sammy."+t,t=n[t]),t.apply(this,e)}catch(i){typeof t=="undefined"?this.error("Plugin Error: called use() but plugin ("+r.toString()+") is not defined",i):u(t)?this.error("Plugin Error",i):this.error("Plugin Error: called use() but '"+r.toString()+"' is not a function",i)}return this},setLocationProxy:function(e){var t=this._location_proxy;this._location_proxy=e,this.isRunning()&&(t&&t.unbind(),this._location_proxy.bind())},log:function(){n.log.apply(n,Array.prototype.concat.apply([this.element_selector],arguments))},route:function(t,n){var s=this,o=[],a,f,l=Array.prototype.slice.call(arguments,2);l.length===0&&u(n)&&(n=t,l=[n],t="any"),t=t.toLowerCase();if(n.constructor==String){i.lastIndex=0;while((f=i.exec(n))!==null)o.push(f[1]);n=new RegExp(n.replace(i,r)+"$")}return e.each(l,function(e,t){typeof t=="string"&&(l[e]=s[t])}),a=function(e){var t={verb:e,path:n,callback:l,param_names:o};s.routes[e]=s.routes[e]||[],s.routes[e].push(t)},t==="any"?e.each(this.ROUTE_VERBS,function(e,t){a(t)}):a(t),this},get:p("get"),post:p("post"),put:p("put"),del:p("delete"),any:p("any"),mapRoutes:function(t){var n=this;return e.each(t,function(e,t){n.route.apply(n,t)}),this},eventNamespace:function(){return["sammy-app",this.namespace].join("-")},bind:function(e,t,n){var r=this;typeof n=="undefined"&&(n=t);var i=function(){var e,t,i;e=arguments[0],i=arguments[1],i&&i.context?(t=i.context,delete i.context):t=new r.context_prototype(r,"bind",e.type,i,e.target),e.cleaned_type=e.type.replace(r.eventNamespace(),""),n.apply(t,[e,i])};return this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(i),this.isRunning()&&this._listen(e,i),this},trigger:function(e,t){return this.$element().trigger([e,this.eventNamespace()].join("."),[t]),this},refresh:function(){return this.last_location=null,this.trigger("location-changed"),this},before:function(e,t){return u(e)&&(t=e,e={}),this.befores.push([e,t]),this},after:function(e){return this.bind("event-context-after",e)},around:function(e){return this.arounds.push(e),this},onComplete:function(e){return this._onComplete=e,this},isRunning:function(){return this._running},helpers:function(t){return e.extend(this.context_prototype.prototype,t),this},helper:function(e,t){return this.context_prototype.prototype[e]=t,this},run:function(r){if(this.isRunning())return!1;var i=this;return e.each(this.listeners.toHash(),function(t,n){e.each(n,function(e,n){i._listen(t,n)})}),this.trigger("run",{start_url:r}),this._running=!0,this.last_location=null,!/\#(.+)/.test(this.getLocation())&&typeof r!="undefined"&&this.setLocation(r),this._checkLocation(),this._location_proxy.bind(),this.bind("location-changed",function(){i._checkLocation()}),this.bind("submit",function(t){if(!n.targetIsThisWindow(t))return!0;var r=i._checkFormSubmission(e(t.target).closest("form"));return r===!1?t.preventDefault():!1}),e(t).bind("unload",function(){i.unload()}),this.trigger("changed")},unload:function(){if(!this.isRunning())return!1;var t=this;return this.trigger("unload"),this._location_proxy.unbind(),this.$element().unbind("submit").removeClass(t.eventNamespace()),e.each(this.listeners.toHash(),function(n,r){e.each(r,function(e,r){t._unlisten(n,r)})}),this._running=!1,this},destroy:function(){return this.unload(),delete n.apps[this.element_selector],this},bindToAllEvents:function(t){var n=this;return e.each(this.APP_EVENTS,function(e,r){n.bind(r,t)}),e.each(this.listeners.keys(!0),function(r,i){e.inArray(i,n.APP_EVENTS)==-1&&n.bind(i,t)}),this},routablePath:function(e){return e.replace(s,"")},lookupRoute:function(e,t){var n=this,r=!1,i=0,s,o;if(typeof this.routes[e]!="undefined"){s=this.routes[e].length;for(;i<s;i++){o=this.routes[e][i];if(n.routablePath(t).match(o.path)){r=o;break}}}return r},runRoute:function(t,n,r,i){var s=this,o=this.lookupRoute(t,n),u,a,f,c,h,p,d,v,m;this.debug&&this.log("runRoute",[t,n].join(" ")),this.trigger("run-route",{verb:t,path:n,params:r}),typeof r=="undefined"&&(r={}),e.extend(r,this._parseQueryString(n));if(o){this.trigger("route-found",{route:o}),(v=o.path.exec(this.routablePath(n)))!==null&&(v.shift(),e.each(v,function(e,t){o.param_names[e]?r[o.param_names[e]]=l(t):(r.splat||(r.splat=[]),r.splat.push(l(t)))})),u=new this.context_prototype(this,t,n,r,i),f=this.arounds.slice(0),h=this.befores.slice(0),d=[u],r.splat&&(d=d.concat(r.splat)),a=function(){var e,t,n;while(h.length>0){p=h.shift();if(s.contextMatchesOptions(u,p[0])){e=p[1].apply(u,[u]);if(e===!1)return!1}}return s.last_route=o,u.trigger("event-context-before",{context:u}),typeof o.callback=="function"&&(o.callback=[o.callback]),o.callback&&o.callback.length&&(t=-1,n=function(){t++,o.callback[t]?e=o.callback[t].apply(u,d):s._onComplete&&typeof (s._onComplete==="function")&&s._onComplete(u)},d.push(n),n()),u.trigger("event-context-after",{context:u}),e},e.each(f.reverse(),function(e,t){var n=a;a=function(){return t.apply(u,[n])}});try{m=a()}catch(g){this.error(["500 Error",t,n].join(" "),g)}return m}return this.notFound(t,n)},contextMatchesOptions:function(t,n,r){var i=n;if(typeof i=="string"||f(i))i={path:i};typeof r=="undefined"&&(r=!0);if(e.isEmptyObject(i))return!0;if(a(i.path)){var s,o,u,l;s=[];for(o=0,l=i.path.length;o<l;o+=1)u=e.extend({},i,{path:i.path[o]}),s.push(this.contextMatchesOptions(t,u));var c=e.inArray(!0,s)>-1?!0:!1;return r?c:!c}if(i.only)return this.contextMatchesOptions(t,i.only,!0);if(i.except)return this.contextMatchesOptions(t,i.except,!1);var h=!0,p=!0;return i.path&&(f(i.path)||(i.path=new RegExp(i.path.toString()+"$")),h=i.path.test(t.path)),i.verb&&(typeof i.verb=="string"?p=i.verb===t.verb:p=i.verb.indexOf(t.verb)>-1),r?p&&h:!p||!h},getLocation:function(){return this._location_proxy.getLocation()},setLocation:function(e){return this._location_proxy.setLocation(e)},swap:function(e,t){var n=this.$element().html(e);return u(t)&&t(e),n},templateCache:function(e,t){return typeof t!="undefined"?d[e]=t:d[e]},clearTemplateCache:function(){return d={}},notFound:function(e,t){var n=this.error(["404 Not Found",e,t].join(" "));return e==="get"?n:!0},error:function(e,t){t||(t=new Error),t.message=[e,t.message].join(" "),this.trigger("error",{message:t.message,error:t});if(this.raise_errors)throw t;this.log(t.message,t)},_checkLocation:function(){var e,t;e=this.getLocation();if(!this.last_location||this.last_location[0]!="get"||this.last_location[1]!=e)this.last_location=["get",e],t=this.runRoute("get",e);return t},_getFormVerb:function(t){var n=e(t),r,i;i=n.find('input[name="_method"]'),i.length>0&&(r=i.val()),r||(r=n[0].getAttribute("method"));if(!r||r==="")r="get";return e.trim(r.toString().toLowerCase())},_checkFormSubmission:function(t){var n,r,i,s,o;return this.trigger("check-form-submission",{form:t}),n=e(t),r=n.attr("action")||"",i=this._getFormVerb(n),this.debug&&this.log("_checkFormSubmission",n,r,i),i==="get"?(s=this._serializeFormParams(n),s!==""&&(r+="?"+s),this.setLocation(r),o=!1):(s=e.extend({},this._parseFormParams(n)),o=this.runRoute(i,r,s,t.get(0))),typeof o=="undefined"?!1:o},_serializeFormParams:function(e){var t="",n=e.serializeArray(),r;if(n.length>0){t=this._encodeFormPair(n[0].name,n[0].value);for(r=1;r<n.length;r++)t=t+"&"+this._encodeFormPair(n[r].name,n[r].value)}return t},_encodeFormPair:function(e,t){return c(e)+"="+c(t)},_parseFormParams:function(e){var t={},n=e.serializeArray(),r;for(r=0;r<n.length;r++)t=this._parseParamPair(t,n[r].name,n[r].value);return t},_parseQueryString:function(e){var t={},n,r,i,o;n=e.match(s);if(n&&n[1]){r=n[1].split("&");for(o=0;o<r.length;o++)i=r[o].split("="),t=this._parseParamPair(t,l(i[0]),l(i[1]||""))}return t},_parseParamPair:function(e,t,n){return typeof e[t]!="undefined"?a(e[t])?e[t].push(n):e[t]=[e[t],n]:e[t]=n,e},_listen:function(e,t){return this.$element().bind([e,this.eventNamespace()].join("."),t)},_unlisten:function(e,t){return this.$element().unbind([e,this.eventNamespace()].join("."),t)}}),n.RenderContext=function(e){this.event_context=e,this.callbacks=[],this.previous_content=null,this.content=null,this.next_engine=!1,this.waiting=!1},n.RenderContext.prototype=e.extend({},n.Object.prototype,{then:function(e){if(!u(e)){if(!(typeof e=="string"&&e in this.event_context))return this;var n=this.event_context[e];e=function(e){return n.apply(this.event_context,[e])}}var r=this;return this.waiting?this.callbacks.push(e):(this.wait(),t.setTimeout(function(){var t=e.apply(r,[r.content,r.previous_content]);t!==!1&&r.next(t)},0)),this},wait:function(){this.waiting=!0},next:function(e){this.waiting=!1,typeof e!="undefined"&&(this.previous_content=this.content,this.content=e),this.callbacks.length>0&&this.then(this.callbacks.shift())},load:function(t,n,r){var i=this;return this.then(function(){var s,o,a,f;u(n)?(r=n,n={}):n=e.extend({},n),r&&this.then(r);if(typeof t=="string")return a=t.match(/\.json$/)||n.json,s=a?n.cache===!0:n.cache!==!1,i.next_engine=i.event_context.engineFor(t),delete n.cache,delete n.json,n.engine&&(i.next_engine=n.engine,delete n.engine),s&&(o=this.event_context.app.templateCache(t))?o:(this.wait(),e.ajax(e.extend({url:t,data:{},dataType:a?"json":"text",type:"get",success:function(e){s&&i.event_context.app.templateCache(t,e),i.next(e)}},n)),!1);if(t.nodeType)return t.innerHTML;if(t.selector)return i.next_engine=t.attr("data-engine"),n.clone===!1?t.remove()[0].innerHTML.toString():t[0].innerHTML.toString()})},loadPartials:function(e){var t;if(e){this.partials=this.partials||{};for(t in e)(function(t,n){t.load(e[n]).then(function(e){this.partials[n]=e})})(this,t)}return this},render:function(e,t,n,r){return u(e)&&!t?this.then(e):(u(t)?(r=n,n=t,t=null):n&&!u(n)&&(r=n,n=null),this.loadPartials(r).load(e).interpolate(t,e).then(n))},partial:function(e,t,n,r){return u(n)?this.render(e,t,r).swap(n):u(t)?this.render(e,{},n).swap(t):this.render(e,t,n).swap()},send:function(){var e=this,t=o(arguments),n=t.shift();return a(t[0])&&(t=t[0]),this.then(function(r){return t.push(function(t){e.next(t)}),e.wait(),n.apply(n,t),!1})},collect:function(t,n,r){var i=this,s=function(){u(t)&&(n=t,t=this.content);var r=[],s=!1;return e.each(t,function(e,t){var o=n.apply(i,[e,t]);return o.jquery&&o.length==1&&(o=o[0],s=!0),r.push(o),o}),s?r:r.join("")};return r?s():this.then(s)},renderEach:function(t,n,r,i){return a(n)&&(i=r,r=n,n=null),this.load(t).then(function(s){var o=this;r||(r=a(this.previous_content)?this.previous_content:[]);if(!i)return this.collect(r,function(e,r){var i={},o=this.next_engine||t;return n?i[n]=r:i=r,this.event_context.interpolate(s,i,o)},!0);e.each(r,function(e,r){var u={},a=this.next_engine||t;n?u[n]=r:u=r,i(r,o.event_context.interpolate(s,u,a))})})},interpolate:function(e,t,n){var r=this;return this.then(function(i,s){!e&&s&&(e=s),this.next_engine&&(t=this.next_engine,this.next_engine=!1);var o=r.event_context.interpolate(i,e,t,this.partials);return n?s+o:o})},swap:function(e){return this.then(function(t){return this.event_context.swap(t,e),t}).trigger("changed",{})},appendTo:function(t){return this.then(function(n){e(t).append(n)}).trigger("changed",{})},prependTo:function(t){return this.then(function(n){e(t).prepend(n)}).trigger("changed",{})},replace:function(t){return this.then(function(n){e(t).html(n)}).trigger("changed",{})},trigger:function(e,t){return this.then(function(n){return typeof t=="undefined"&&(t={content:n}),this.event_context.trigger(e,t),n})}}),n.EventContext=function(e,t,r,i,s){this.app=e,this.verb=t,this.path=r,this.params=new n.Object(i),this.target=s},n.EventContext.prototype=e.extend({},n.Object.prototype,{$element:function(){return this.app.$element(o(arguments).shift())},engineFor:function(e){var t=this,n;if(u(e))return e;e=(e||t.app.template_engine).toString();if(n=e.match(/\.([^\.\?\#]+)$/))e=n[1];return e&&u(t[e])?t[e]:t.app.template_engine?this.engineFor(t.app.template_engine):function(e,t){return e}},interpolate:function(e,t,n,r){return this.engineFor(n).apply(this,[e,t,r])},render:function(e,t,r,i){return(new n.RenderContext(this)).render(e,t,r,i)},renderEach:function(e,t,r,i){return(new n.RenderContext(this)).renderEach(e,t,r,i)},load:function(e,t,r){return(new n.RenderContext(this)).load(e,t,r)},loadPartials:function(e){return(new n.RenderContext(this)).loadPartials(e)},partial:function(e,t,r,i){return(new n.RenderContext(this)).partial(e,t,r,i)},send:function(){var e=new n.RenderContext(this);return e.send.apply(e,arguments)},redirect:function(){var t,n=o(arguments),r=this.app.getLocation(),i=n.length;if(i>1){var s=0,u=[],a=[],f={},l=!1;for(;s<i;s++)typeof n[s]=="string"?u.push(n[s]):(e.extend(f,n[s]),l=!0);t=u.join("/");if(l){for(var c in f)a.push(this.app._encodeFormPair(c,f[c]));t+="?"+a.join("&")}}else t=n[0];this.trigger("redirect",{to:t}),this.app.last_location=[this.verb,this.path],this.app.setLocation(t),(new RegExp(t)).test(r)&&this.app.trigger("location-changed")},trigger:function(e,t){return typeof t=="undefined"&&(t={}),t.context||(t.context=this),this.app.trigger(e,t)},eventNamespace:function(){return this.app.eventNamespace()},swap:function(e,t){return this.app.swap(e,t)},notFound:function(){return this.app.notFound(this.verb,this.path)},json:function(t){return e.parseJSON(t)},toString:function(){return"Sammy.EventContext: "+[this.verb,this.path,this.params].join(" ")}}),n})})(jQuery,window);