soca 0.1.0

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