sammyjs-rails 0.7.5

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