soca 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,1403 @@
1
+ // name: sammy
2
+ // version: 0.5.4
3
+
4
+ (function($) {
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
+ _routeWrapper = function(verb) {
17
+ return function(path, callback) { return this.route.apply(this, [verb, path, callback]); };
18
+ },
19
+ loggers = [];
20
+
21
+
22
+ // `Sammy` (also aliased as $.sammy) is not only the namespace for a
23
+ // number of prototypes, its also a top level method that allows for easy
24
+ // creation/management of `Sammy.Application` instances. There are a
25
+ // number of different forms for `Sammy()` but each returns an instance
26
+ // of `Sammy.Application`. When a new instance is created using
27
+ // `Sammy` it is added to an Object called `Sammy.apps`. This
28
+ // provides for an easy way to get at existing Sammy applications. Only one
29
+ // instance is allowed per `element_selector` so when calling
30
+ // `Sammy('selector')` multiple times, the first time will create
31
+ // the application and the following times will extend the application
32
+ // already added to that selector.
33
+ //
34
+ // ### Example
35
+ //
36
+ // // returns the app at #main or a new app
37
+ // Sammy('#main')
38
+ //
39
+ // // equivilent to "new Sammy.Application", except appends to apps
40
+ // Sammy();
41
+ // Sammy(function() { ... });
42
+ //
43
+ // // extends the app at '#main' with function.
44
+ // Sammy('#main', function() { ... });
45
+ //
46
+ Sammy = function() {
47
+ var args = _makeArray(arguments),
48
+ app, selector;
49
+ Sammy.apps = Sammy.apps || {};
50
+ if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
51
+ return Sammy.apply(Sammy, ['body'].concat(args));
52
+ } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
53
+ app = Sammy.apps[selector] || new Sammy.Application();
54
+ app.element_selector = selector;
55
+ if (args.length > 0) {
56
+ $.each(args, function(i, plugin) {
57
+ app.use(plugin);
58
+ });
59
+ }
60
+ // if the selector changes make sure the refrence in Sammy.apps changes
61
+ if (app.element_selector != selector) {
62
+ delete Sammy.apps[selector];
63
+ }
64
+ Sammy.apps[app.element_selector] = app;
65
+ return app;
66
+ }
67
+ };
68
+
69
+ Sammy.VERSION = '0.5.4';
70
+
71
+ // Add to the global logger pool. Takes a function that accepts an
72
+ // unknown number of arguments and should print them or send them somewhere
73
+ // The first argument is always a timestamp.
74
+ Sammy.addLogger = function(logger) {
75
+ loggers.push(logger);
76
+ };
77
+
78
+ // Sends a log message to each logger listed in the global
79
+ // loggers pool. Can take any number of arguments.
80
+ // Also prefixes the arguments with a timestamp.
81
+ Sammy.log = function() {
82
+ var args = _makeArray(arguments);
83
+ args.unshift("[" + Date() + "]");
84
+ $.each(loggers, function(i, logger) {
85
+ logger.apply(Sammy, args);
86
+ });
87
+ };
88
+
89
+ if (typeof window.console != 'undefined') {
90
+ if (_isFunction(console.log.apply)) {
91
+ Sammy.addLogger(function() {
92
+ window.console.log.apply(console, arguments);
93
+ });
94
+ } else {
95
+ Sammy.addLogger(function() {
96
+ window.console.log(arguments);
97
+ });
98
+ }
99
+ } else if (typeof console != 'undefined') {
100
+ Sammy.addLogger(function() {
101
+ console.log.apply(console, arguments);
102
+ });
103
+ }
104
+
105
+ $.extend(Sammy, {
106
+ makeArray: _makeArray,
107
+ isFunction: _isFunction,
108
+ isArray: _isArray
109
+ })
110
+
111
+ // Sammy.Object is the base for all other Sammy classes. It provides some useful
112
+ // functionality, including cloning, iterating, etc.
113
+ Sammy.Object = function(obj) { // constructor
114
+ return $.extend(this, obj || {});
115
+ };
116
+
117
+ $.extend(Sammy.Object.prototype, {
118
+
119
+ // Returns a copy of the object with Functions removed.
120
+ toHash: function() {
121
+ var json = {};
122
+ $.each(this, function(k,v) {
123
+ if (!_isFunction(v)) {
124
+ json[k] = v;
125
+ }
126
+ });
127
+ return json;
128
+ },
129
+
130
+ // Renders a simple HTML version of this Objects attributes.
131
+ // Does not render functions.
132
+ // For example. Given this Sammy.Object:
133
+ //
134
+ // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
135
+ // s.toHTML() //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
136
+ //
137
+ toHTML: function() {
138
+ var display = "";
139
+ $.each(this, function(k, v) {
140
+ if (!_isFunction(v)) {
141
+ display += "<strong>" + k + "</strong> " + v + "<br />";
142
+ }
143
+ });
144
+ return display;
145
+ },
146
+
147
+ // Returns an array of keys for this object. If `attributes_only`
148
+ // is true will not return keys that map to a `function()`
149
+ keys: function(attributes_only) {
150
+ var keys = [];
151
+ for (var property in this) {
152
+ if (!_isFunction(this[property]) || !attributes_only) {
153
+ keys.push(property);
154
+ }
155
+ }
156
+ return keys;
157
+ },
158
+
159
+ // Checks if the object has a value at `key` and that the value is not empty
160
+ has: function(key) {
161
+ return this[key] && $.trim(this[key].toString()) != '';
162
+ },
163
+
164
+ // convenience method to join as many arguments as you want
165
+ // by the first argument - useful for making paths
166
+ join: function() {
167
+ var args = _makeArray(arguments);
168
+ var delimiter = args.shift();
169
+ return args.join(delimiter);
170
+ },
171
+
172
+ // Shortcut to Sammy.log
173
+ log: function() {
174
+ Sammy.log.apply(Sammy, arguments);
175
+ },
176
+
177
+ // Returns a string representation of this object.
178
+ // if `include_functions` is true, it will also toString() the
179
+ // methods of this object. By default only prints the attributes.
180
+ toString: function(include_functions) {
181
+ var s = [];
182
+ $.each(this, function(k, v) {
183
+ if (!_isFunction(v) || include_functions) {
184
+ s.push('"' + k + '": ' + v.toString());
185
+ }
186
+ });
187
+ return "Sammy.Object: {" + s.join(',') + "}";
188
+ }
189
+ });
190
+
191
+ // The HashLocationProxy is the default location proxy for all Sammy applications.
192
+ // A location proxy is a prototype that conforms to a simple interface. The purpose
193
+ // of a location proxy is to notify the Sammy.Application its bound to when the location
194
+ // or 'external state' changes. The HashLocationProxy considers the state to be
195
+ // changed when the 'hash' (window.location.hash / '#') changes. It does this in two
196
+ // different ways depending on what browser you are using. The newest browsers
197
+ // (IE, Safari > 4, FF >= 3.6) support a 'onhashchange' DOM event, thats fired whenever
198
+ // the location.hash changes. In this situation the HashLocationProxy just binds
199
+ // to this event and delegates it to the application. In the case of older browsers
200
+ // a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier,
201
+ // the HashLocationProxy allows the poller to be a global object, eliminating the
202
+ // need for multiple pollers even when thier are multiple apps on the page.
203
+ Sammy.HashLocationProxy = function(app, run_interval_every) {
204
+ this.app = app;
205
+ // set is native to false and start the poller immediately
206
+ this.is_native = false;
207
+ this._startPolling(run_interval_every);
208
+ };
209
+
210
+ Sammy.HashLocationProxy.prototype = {
211
+ // bind the proxy events to the current app.
212
+ bind: function() {
213
+ var proxy = this, app = this.app;
214
+ $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
215
+ // if we receive a native hash change event, set the proxy accordingly
216
+ // and stop polling
217
+ if (proxy.is_native === false && !non_native) {
218
+ Sammy.log('native hash change exists, using');
219
+ proxy.is_native = true;
220
+ clearInterval(Sammy.HashLocationProxy._interval);
221
+ }
222
+ app.trigger('location-changed');
223
+ });
224
+ },
225
+ // unbind the proxy events from the current app
226
+ unbind: function() {
227
+ $(window).unbind('hashchange.' + this.app.eventNamespace());
228
+ },
229
+ // get the current location from the hash.
230
+ getLocation: function() {
231
+ // Bypass the `window.location.hash` attribute. If a question mark
232
+ // appears in the hash IE6 will strip it and all of the following
233
+ // characters from `window.location.hash`.
234
+ var matches = window.location.toString().match(/^[^#]*(#.+)$/);
235
+ return matches ? matches[1] : '';
236
+ },
237
+ // set the current location to `new_location`
238
+ setLocation: function(new_location) {
239
+ return (window.location = new_location);
240
+ },
241
+
242
+ _startPolling: function(every) {
243
+ // set up interval
244
+ var proxy = this;
245
+ if (!Sammy.HashLocationProxy._interval) {
246
+ if (!every) { every = 10; }
247
+ var hashCheck = function() {
248
+ current_location = proxy.getLocation();
249
+ if (!Sammy.HashLocationProxy._last_location ||
250
+ current_location != Sammy.HashLocationProxy._last_location) {
251
+ setTimeout(function() {
252
+ $(window).trigger('hashchange', [true]);
253
+ }, 1);
254
+ }
255
+ Sammy.HashLocationProxy._last_location = current_location;
256
+ };
257
+ hashCheck();
258
+ Sammy.HashLocationProxy._interval = setInterval(hashCheck, every);
259
+ $(window).bind('beforeunload', function() {
260
+ clearInterval(Sammy.HashLocationProxy._interval);
261
+ });
262
+ }
263
+ }
264
+ };
265
+
266
+ // The DataLocationProxy is an optional location proxy prototype. As opposed to
267
+ // the `HashLocationProxy` it gets its location from a jQuery.data attribute
268
+ // tied to the application's element. You can set the name of the attribute by
269
+ // passing a string as the second argument to the constructor. The default attribute
270
+ // name is 'sammy-location'. To read more about location proxies, check out the
271
+ // documentation for `Sammy.HashLocationProxy`
272
+ Sammy.DataLocationProxy = function(app, data_name) {
273
+ this.app = app;
274
+ this.data_name = data_name || 'sammy-location';
275
+ };
276
+
277
+ Sammy.DataLocationProxy.prototype = {
278
+ bind: function() {
279
+ var proxy = this;
280
+ this.app.$element().bind('setData', function(e, key, value) {
281
+ if (key == proxy.data_name) {
282
+ // jQuery unfortunately fires the event before it sets the value
283
+ // work around it, by setting the value ourselves
284
+ proxy.app.$element().each(function() {
285
+ $.data(this, proxy.data_name, value);
286
+ });
287
+ proxy.app.trigger('location-changed');
288
+ }
289
+ });
290
+ },
291
+
292
+ unbind: function() {
293
+ this.app.$element().unbind('setData');
294
+ },
295
+
296
+ getLocation: function() {
297
+ return this.app.$element().data(this.data_name);
298
+ },
299
+
300
+ setLocation: function(new_location) {
301
+ return this.app.$element().data(this.data_name, new_location);
302
+ }
303
+ };
304
+
305
+ // Sammy.Application is the Base prototype for defining 'applications'.
306
+ // An 'application' is a collection of 'routes' and bound events that is
307
+ // attached to an element when `run()` is called.
308
+ // The only argument an 'app_function' is evaluated within the context of the application.
309
+ Sammy.Application = function(app_function) {
310
+ var app = this;
311
+ this.routes = {};
312
+ this.listeners = new Sammy.Object({});
313
+ this.arounds = [];
314
+ this.befores = [];
315
+ // generate a unique namespace
316
+ this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
317
+ this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
318
+ this.context_prototype.prototype = new Sammy.EventContext();
319
+
320
+ if (_isFunction(app_function)) {
321
+ app_function.apply(this, [this]);
322
+ }
323
+ // set the location proxy if not defined to the default (HashLocationProxy)
324
+ if (!this.location_proxy) {
325
+ this.location_proxy = new Sammy.HashLocationProxy(app, this.run_interval_every);
326
+ }
327
+ if (this.debug) {
328
+ this.bindToAllEvents(function(e, data) {
329
+ app.log(app.toString(), e.cleaned_type, data || {});
330
+ });
331
+ }
332
+ };
333
+
334
+ Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
335
+
336
+ // the four route verbs
337
+ ROUTE_VERBS: ['get','post','put','delete'],
338
+
339
+ // An array of the default events triggered by the
340
+ // application during its lifecycle
341
+ APP_EVENTS: ['run','unload','lookup-route','run-route','route-found','event-context-before','event-context-after','changed','error','check-form-submission','redirect'],
342
+
343
+ _last_route: null,
344
+ _running: false,
345
+
346
+ // Defines what element the application is bound to. Provide a selector
347
+ // (parseable by `jQuery()`) and this will be used by `$element()`
348
+ element_selector: 'body',
349
+
350
+ // When set to true, logs all of the default events using `log()`
351
+ debug: false,
352
+
353
+ // When set to true, and the error() handler is not overriden, will actually
354
+ // raise JS errors in routes (500) and when routes can't be found (404)
355
+ raise_errors: false,
356
+
357
+ // The time in milliseconds that the URL is queried for changes
358
+ run_interval_every: 50,
359
+
360
+ // The location proxy for the current app. By default this is set to a new
361
+ // `Sammy.HashLocationProxy` on initialization. However, you can set
362
+ // the location_proxy inside you're app function to give youre app a custom
363
+ // location mechanism
364
+ location_proxy: null,
365
+
366
+ // The default template engine to use when using `partial()` in an
367
+ // `EventContext`. `template_engine` can either be a string that
368
+ // corresponds to the name of a method/helper on EventContext or it can be a function
369
+ // that takes two arguments, the content of the unrendered partial and an optional
370
+ // JS object that contains interpolation data. Template engine is only called/refered
371
+ // to if the extension of the partial is null or unknown. See `partial()`
372
+ // for more information
373
+ template_engine: null,
374
+
375
+ // //=> Sammy.Application: body
376
+ toString: function() {
377
+ return 'Sammy.Application:' + this.element_selector;
378
+ },
379
+
380
+ // returns a jQuery object of the Applications bound element.
381
+ $element: function() {
382
+ return $(this.element_selector);
383
+ },
384
+
385
+ // `use()` is the entry point for including Sammy plugins.
386
+ // The first argument to use should be a function() that is evaluated
387
+ // in the context of the current application, just like the `app_function`
388
+ // argument to the `Sammy.Application` constructor.
389
+ //
390
+ // Any additional arguments are passed to the app function sequentially.
391
+ //
392
+ // For much more detail about plugins, check out:
393
+ // http://code.quirkey.com/sammy/doc/plugins.html
394
+ //
395
+ // ### Example
396
+ //
397
+ // var MyPlugin = function(app, prepend) {
398
+ //
399
+ // this.helpers({
400
+ // myhelper: function(text) {
401
+ // alert(prepend + " " + text);
402
+ // }
403
+ // });
404
+ //
405
+ // };
406
+ //
407
+ // var app = $.sammy(function() {
408
+ //
409
+ // this.use(MyPlugin, 'This is my plugin');
410
+ //
411
+ // this.get('#/', function() {
412
+ // this.myhelper('and dont you forget it!');
413
+ // //=> Alerts: This is my plugin and dont you forget it!
414
+ // });
415
+ //
416
+ // });
417
+ //
418
+ use: function() {
419
+ // flatten the arguments
420
+ var args = _makeArray(arguments);
421
+ var plugin = args.shift();
422
+ try {
423
+ args.unshift(this);
424
+ plugin.apply(this, args);
425
+ } catch(e) {
426
+ if (typeof plugin == 'undefined') {
427
+ this.error("Plugin Error: called use() but plugin is not defined", e);
428
+ } else if (!_isFunction(plugin)) {
429
+ this.error("Plugin Error: called use() but '" + plugin.toString() + "' is not a function", e);
430
+ } else {
431
+ this.error("Plugin Error", e);
432
+ }
433
+ }
434
+ return this;
435
+ },
436
+
437
+ // `route()` is the main method for defining routes within an application.
438
+ // For great detail on routes, check out: http://code.quirkey.com/sammy/doc/routes.html
439
+ //
440
+ // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
441
+ //
442
+ // ### Arguments
443
+ //
444
+ // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
445
+ // of the ROUTE_VERBS. If only two arguments are passed,
446
+ // the first argument is the path, the second is the callback and the verb
447
+ // is assumed to be 'any'.
448
+ // * `path` A Regexp or a String representing the path to match to invoke this verb.
449
+ // * `callback` A Function that is called/evaluated whent the route is run see: `runRoute()`.
450
+ // It is also possible to pass a string as the callback, which is looked up as the name
451
+ // of a method on the application.
452
+ //
453
+ route: function(verb, path, callback) {
454
+ var app = this, param_names = [], add_route;
455
+
456
+ // if the method signature is just (path, callback)
457
+ // assume the verb is 'any'
458
+ if (!callback && _isFunction(path)) {
459
+ path = verb;
460
+ callback = path;
461
+ verb = 'any';
462
+ }
463
+
464
+ verb = verb.toLowerCase(); // ensure verb is lower case
465
+
466
+ // if path is a string turn it into a regex
467
+ if (path.constructor == String) {
468
+
469
+ // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
470
+ // 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
471
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
472
+ PATH_NAME_MATCHER.lastIndex = 0;
473
+
474
+ // find the names
475
+ while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
476
+ param_names.push(path_match[1]);
477
+ }
478
+ // replace with the path replacement
479
+ path = new RegExp("^" + path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
480
+ }
481
+ // lookup callback
482
+ if (typeof callback == 'string') {
483
+ callback = app[callback];
484
+ }
485
+
486
+ add_route = function(with_verb) {
487
+ var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
488
+ // add route to routes array
489
+ app.routes[with_verb] = app.routes[with_verb] || [];
490
+ // place routes in order of definition
491
+ app.routes[with_verb].push(r);
492
+ };
493
+
494
+ if (verb === 'any') {
495
+ $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
496
+ } else {
497
+ add_route(verb);
498
+ }
499
+
500
+ // return the app
501
+ return this;
502
+ },
503
+
504
+ // Alias for route('get', ...)
505
+ get: _routeWrapper('get'),
506
+
507
+ // Alias for route('post', ...)
508
+ post: _routeWrapper('post'),
509
+
510
+ // Alias for route('put', ...)
511
+ put: _routeWrapper('put'),
512
+
513
+ // Alias for route('delete', ...)
514
+ del: _routeWrapper('delete'),
515
+
516
+ // Alias for route('any', ...)
517
+ any: _routeWrapper('any'),
518
+
519
+ // `mapRoutes` takes an array of arrays, each array being passed to route()
520
+ // as arguments, this allows for mass definition of routes. Another benefit is
521
+ // this makes it possible/easier to load routes via remote JSON.
522
+ //
523
+ // ### Example
524
+ //
525
+ // var app = $.sammy(function() {
526
+ //
527
+ // this.mapRoutes([
528
+ // ['get', '#/', function() { this.log('index'); }],
529
+ // // strings in callbacks are looked up as methods on the app
530
+ // ['post', '#/create', 'addUser'],
531
+ // // No verb assumes 'any' as the verb
532
+ // [/dowhatever/, function() { this.log(this.verb, this.path)}];
533
+ // ]);
534
+ // })
535
+ //
536
+ mapRoutes: function(route_array) {
537
+ var app = this;
538
+ $.each(route_array, function(i, route_args) {
539
+ app.route.apply(app, route_args);
540
+ });
541
+ return this;
542
+ },
543
+
544
+ // A unique event namespace defined per application.
545
+ // All events bound with `bind()` are automatically bound within this space.
546
+ eventNamespace: function() {
547
+ return ['sammy-app', this.namespace].join('-');
548
+ },
549
+
550
+ // Works just like `jQuery.fn.bind()` with a couple noteable differences.
551
+ //
552
+ // * It binds all events to the application element
553
+ // * All events are bound within the `eventNamespace()`
554
+ // * Events are not actually bound until the application is started with `run()`
555
+ // * callbacks are evaluated within the context of a Sammy.EventContext
556
+ //
557
+ // See http://code.quirkey.com/sammy/docs/events.html for more info.
558
+ //
559
+ bind: function(name, data, callback) {
560
+ var app = this;
561
+ // build the callback
562
+ // if the arity is 2, callback is the second argument
563
+ if (typeof callback == 'undefined') { callback = data; }
564
+ var listener_callback = function() {
565
+ // pull off the context from the arguments to the callback
566
+ var e, context, data;
567
+ e = arguments[0];
568
+ data = arguments[1];
569
+ if (data && data.context) {
570
+ context = data.context;
571
+ delete data.context;
572
+ } else {
573
+ context = new app.context_prototype(app, 'bind', e.type, data, e.target);
574
+ }
575
+ e.cleaned_type = e.type.replace(app.eventNamespace(), '');
576
+ callback.apply(context, [e, data]);
577
+ };
578
+
579
+ // it could be that the app element doesnt exist yet
580
+ // so attach to the listeners array and then run()
581
+ // will actually bind the event.
582
+ if (!this.listeners[name]) { this.listeners[name] = []; }
583
+ this.listeners[name].push(listener_callback);
584
+ if (this.isRunning()) {
585
+ // if the app is running
586
+ // *actually* bind the event to the app element
587
+ this._listen(name, listener_callback);
588
+ }
589
+ return this;
590
+ },
591
+
592
+ // Triggers custom events defined with `bind()`
593
+ //
594
+ // ### Arguments
595
+ //
596
+ // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
597
+ // * `data` An optional Object that can be passed to the bound callback.
598
+ // * `context` An optional context/Object in which to execute the bound callback.
599
+ // If no context is supplied a the context is a new `Sammy.EventContext`
600
+ //
601
+ trigger: function(name, data) {
602
+ this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
603
+ return this;
604
+ },
605
+
606
+ // Reruns the current route
607
+ refresh: function() {
608
+ this.last_location = null;
609
+ this.trigger('location-changed');
610
+ return this;
611
+ },
612
+
613
+ // Takes a single callback that is pushed on to a stack.
614
+ // Before any route is run, the callbacks are evaluated in order within
615
+ // the current `Sammy.EventContext`
616
+ //
617
+ // If any of the callbacks explicitly return false, execution of any
618
+ // further callbacks and the route itself is halted.
619
+ //
620
+ // You can also provide a set of options that will define when to run this
621
+ // before based on the route it proceeds.
622
+ //
623
+ // ### Example
624
+ //
625
+ // var app = $.sammy(function() {
626
+ //
627
+ // // will run at #/route but not at #/
628
+ // this.before('#/route', function() {
629
+ // //...
630
+ // });
631
+ //
632
+ // // will run at #/ but not at #/route
633
+ // this.before({except: {path: '#/route'}}, function() {
634
+ // this.log('not before #/route');
635
+ // });
636
+ //
637
+ // this.get('#/', function() {});
638
+ //
639
+ // this.get('#/route', function() {});
640
+ //
641
+ // });
642
+ //
643
+ // See `contextMatchesOptions()` for a full list of supported options
644
+ //
645
+ before: function(options, callback) {
646
+ if (_isFunction(options)) {
647
+ callback = options;
648
+ options = {};
649
+ }
650
+ this.befores.push([options, callback]);
651
+ return this;
652
+ },
653
+
654
+ // A shortcut for binding a callback to be run after a route is executed.
655
+ // After callbacks have no guarunteed order.
656
+ after: function(callback) {
657
+ return this.bind('event-context-after', callback);
658
+ },
659
+
660
+
661
+ // Adds an around filter to the application. around filters are functions
662
+ // that take a single argument `callback` which is the entire route
663
+ // execution path wrapped up in a closure. This means you can decide whether
664
+ // or not to proceed with execution by not invoking `callback` or,
665
+ // more usefuly wrapping callback inside the result of an asynchronous execution.
666
+ //
667
+ // ### Example
668
+ //
669
+ // The most common use case for around() is calling a _possibly_ async function
670
+ // and executing the route within the functions callback:
671
+ //
672
+ // var app = $.sammy(function() {
673
+ //
674
+ // var current_user = false;
675
+ //
676
+ // function checkLoggedIn(callback) {
677
+ // // /session returns a JSON representation of the logged in user
678
+ // // or an empty object
679
+ // if (!current_user) {
680
+ // $.getJSON('/session', function(json) {
681
+ // if (json.login) {
682
+ // // show the user as logged in
683
+ // current_user = json;
684
+ // // execute the route path
685
+ // callback();
686
+ // } else {
687
+ // // show the user as not logged in
688
+ // current_user = false;
689
+ // // the context of aroundFilters is an EventContext
690
+ // this.redirect('#/login');
691
+ // }
692
+ // });
693
+ // } else {
694
+ // // execute the route path
695
+ // callback();
696
+ // }
697
+ // };
698
+ //
699
+ // this.around(checkLoggedIn);
700
+ //
701
+ // });
702
+ //
703
+ around: function(callback) {
704
+ this.arounds.push(callback);
705
+ return this;
706
+ },
707
+
708
+ // Returns a boolean of weather the current application is running.
709
+ isRunning: function() {
710
+ return this._running;
711
+ },
712
+
713
+ // Helpers extends the EventContext prototype specific to this app.
714
+ // This allows you to define app specific helper functions that can be used
715
+ // whenever you're inside of an event context (templates, routes, bind).
716
+ //
717
+ // ### Example
718
+ //
719
+ // var app = $.sammy(function() {
720
+ //
721
+ // helpers({
722
+ // upcase: function(text) {
723
+ // return text.toString().toUpperCase();
724
+ // }
725
+ // });
726
+ //
727
+ // get('#/', function() { with(this) {
728
+ // // inside of this context I can use the helpers
729
+ // $('#main').html(upcase($('#main').text());
730
+ // }});
731
+ //
732
+ // });
733
+ //
734
+ //
735
+ // ### Arguments
736
+ //
737
+ // * `extensions` An object collection of functions to extend the context.
738
+ //
739
+ helpers: function(extensions) {
740
+ $.extend(this.context_prototype.prototype, extensions);
741
+ return this;
742
+ },
743
+
744
+ // Helper extends the event context just like `helpers()` but does it
745
+ // a single method at a time. This is especially useful for dynamically named
746
+ // helpers
747
+ //
748
+ // ### Example
749
+ //
750
+ // // Trivial example that adds 3 helper methods to the context dynamically
751
+ // var app = $.sammy(function(app) {
752
+ //
753
+ // $.each([1,2,3], function(i, num) {
754
+ // app.helper('helper' + num, function() {
755
+ // this.log("I'm helper number " + num);
756
+ // });
757
+ // });
758
+ //
759
+ // this.get('#/', function() {
760
+ // this.helper2(); //=> I'm helper number 2
761
+ // });
762
+ // });
763
+ //
764
+ // ### Arguments
765
+ //
766
+ // * `name` The name of the method
767
+ // * `method` The function to be added to the prototype at `name`
768
+ //
769
+ helper: function(name, method) {
770
+ this.context_prototype.prototype[name] = method;
771
+ return this;
772
+ },
773
+
774
+ // Actually starts the application's lifecycle. `run()` should be invoked
775
+ // within a document.ready block to ensure the DOM exists before binding events, etc.
776
+ //
777
+ // ### Example
778
+ //
779
+ // var app = $.sammy(function() { ... }); // your application
780
+ // $(function() { // document.ready
781
+ // app.run();
782
+ // });
783
+ //
784
+ // ### Arguments
785
+ //
786
+ // * `start_url` Optionally, a String can be passed which the App will redirect to
787
+ // after the events/routes have been bound.
788
+ run: function(start_url) {
789
+ if (this.isRunning()) { return false; }
790
+ var app = this;
791
+
792
+ // actually bind all the listeners
793
+ $.each(this.listeners.toHash(), function(name, callbacks) {
794
+ $.each(callbacks, function(i, listener_callback) {
795
+ app._listen(name, listener_callback);
796
+ });
797
+ });
798
+
799
+ this.trigger('run', {start_url: start_url});
800
+ this._running = true;
801
+ // set last location
802
+ this.last_location = null;
803
+ if (this.getLocation() == '' && typeof start_url != 'undefined') {
804
+ this.setLocation(start_url);
805
+ }
806
+ // check url
807
+ this._checkLocation();
808
+ this.location_proxy.bind();
809
+ this.bind('location-changed', function() {
810
+ app._checkLocation();
811
+ });
812
+
813
+ // bind to submit to capture post/put/delete routes
814
+ this.bind('submit', function(e) {
815
+ var returned = app._checkFormSubmission($(e.target).closest('form'));
816
+ return (returned === false) ? e.preventDefault() : false;
817
+ });
818
+
819
+ // bind unload to body unload
820
+ $(window).bind('beforeunload', function() {
821
+ app.unload();
822
+ });
823
+
824
+ // trigger html changed
825
+ return this.trigger('changed');
826
+ },
827
+
828
+ // The opposite of `run()`, un-binds all event listeners and intervals
829
+ // `run()` Automaticaly binds a `onunload` event to run this when
830
+ // the document is closed.
831
+ unload: function() {
832
+ if (!this.isRunning()) { return false; }
833
+ var app = this;
834
+ this.trigger('unload');
835
+ // clear interval
836
+ this.location_proxy.unbind();
837
+ // unbind form submits
838
+ this.$element().unbind('submit').removeClass(app.eventNamespace());
839
+ // unbind all events
840
+ $.each(this.listeners.toHash() , function(name, listeners) {
841
+ $.each(listeners, function(i, listener_callback) {
842
+ app._unlisten(name, listener_callback);
843
+ });
844
+ });
845
+ this._running = false;
846
+ return this;
847
+ },
848
+
849
+ // Will bind a single callback function to every event that is already
850
+ // being listened to in the app. This includes all the `APP_EVENTS`
851
+ // as well as any custom events defined with `bind()`.
852
+ //
853
+ // Used internally for debug logging.
854
+ bindToAllEvents: function(callback) {
855
+ var app = this;
856
+ // bind to the APP_EVENTS first
857
+ $.each(this.APP_EVENTS, function(i, e) {
858
+ app.bind(e, callback);
859
+ });
860
+ // next, bind to listener names (only if they dont exist in APP_EVENTS)
861
+ $.each(this.listeners.keys(true), function(i, name) {
862
+ if (app.APP_EVENTS.indexOf(name) == -1) {
863
+ app.bind(name, callback);
864
+ }
865
+ });
866
+ return this;
867
+ },
868
+
869
+ // Returns a copy of the given path with any query string after the hash
870
+ // removed.
871
+ routablePath: function(path) {
872
+ return path.replace(QUERY_STRING_MATCHER, '');
873
+ },
874
+
875
+ // Given a verb and a String path, will return either a route object or false
876
+ // if a matching route can be found within the current defined set.
877
+ lookupRoute: function(verb, path) {
878
+ var app = this, routed = false;
879
+ this.trigger('lookup-route', {verb: verb, path: path});
880
+ if (typeof this.routes[verb] != 'undefined') {
881
+ $.each(this.routes[verb], function(i, route) {
882
+ if (app.routablePath(path).match(route.path)) {
883
+ routed = route;
884
+ return false;
885
+ }
886
+ });
887
+ }
888
+ return routed;
889
+ },
890
+
891
+ // First, invokes `lookupRoute()` and if a route is found, parses the
892
+ // possible URL params and then invokes the route's callback within a new
893
+ // `Sammy.EventContext`. If the route can not be found, it calls
894
+ // `notFound()`. If `raise_errors` is set to `true` and
895
+ // the `error()` has not been overriden, it will throw an actual JS
896
+ // error.
897
+ //
898
+ // You probably will never have to call this directly.
899
+ //
900
+ // ### Arguments
901
+ //
902
+ // * `verb` A String for the verb.
903
+ // * `path` A String path to lookup.
904
+ // * `params` An Object of Params pulled from the URI or passed directly.
905
+ //
906
+ // ### Returns
907
+ //
908
+ // Either returns the value returned by the route callback or raises a 404 Not Found error.
909
+ //
910
+ runRoute: function(verb, path, params, target) {
911
+ var app = this,
912
+ route = this.lookupRoute(verb, path),
913
+ context,
914
+ wrapped_route,
915
+ arounds,
916
+ around,
917
+ befores,
918
+ before,
919
+ callback_args,
920
+ final_returned;
921
+
922
+ this.log('runRoute', [verb, path].join(' '));
923
+ this.trigger('run-route', {verb: verb, path: path, params: params});
924
+ if (typeof params == 'undefined') { params = {}; }
925
+
926
+ $.extend(params, this._parseQueryString(path));
927
+
928
+ if (route) {
929
+ this.trigger('route-found', {route: route});
930
+ // pull out the params from the path
931
+ if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
932
+ // first match is the full path
933
+ path_params.shift();
934
+ // for each of the matches
935
+ $.each(path_params, function(i, param) {
936
+ // if theres a matching param name
937
+ if (route.param_names[i]) {
938
+ // set the name to the match
939
+ params[route.param_names[i]] = _decode(param);
940
+ } else {
941
+ // initialize 'splat'
942
+ if (!params.splat) { params.splat = []; }
943
+ params.splat.push(_decode(param));
944
+ }
945
+ });
946
+ }
947
+
948
+ // set event context
949
+ context = new this.context_prototype(this, verb, path, params, target);
950
+ // ensure arrays
951
+ arounds = this.arounds.slice(0);
952
+ befores = this.befores.slice(0);
953
+ // set the callback args to the context + contents of the splat
954
+ callback_args = [context].concat(params.splat);
955
+ // wrap the route up with the before filters
956
+ wrapped_route = function() {
957
+ var returned;
958
+ while (befores.length > 0) {
959
+ before = befores.shift();
960
+ // check the options
961
+ if (app.contextMatchesOptions(context, before[0])) {
962
+ returned = before[1].apply(context, [context]);
963
+ if (returned === false) { return false; }
964
+ }
965
+ }
966
+ app.last_route = route;
967
+ context.trigger('event-context-before', {context: context});
968
+ returned = route.callback.apply(context, callback_args);
969
+ context.trigger('event-context-after', {context: context});
970
+ return returned;
971
+ };
972
+ $.each(arounds.reverse(), function(i, around) {
973
+ var last_wrapped_route = wrapped_route;
974
+ wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
975
+ });
976
+ try {
977
+ final_returned = wrapped_route();
978
+ } catch(e) {
979
+ this.error(['500 Error', verb, path].join(' '), e);
980
+ }
981
+ return final_returned;
982
+ } else {
983
+ return this.notFound(verb, path);
984
+ }
985
+ },
986
+
987
+ // Matches an object of options against an `EventContext` like object that
988
+ // contains `path` and `verb` attributes. Internally Sammy uses this
989
+ // for matching `before()` filters against specific options. You can set the
990
+ // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
991
+ // those that match the options.
992
+ //
993
+ // ### Example
994
+ //
995
+ // var app = $.sammy(),
996
+ // context = {verb: 'get', path: '#/mypath'};
997
+ //
998
+ // // match against a path string
999
+ // app.contextMatchesOptions(context, '#/mypath'); //=> true
1000
+ // app.contextMatchesOptions(context, '#/otherpath'); //=> false
1001
+ // // equivilent to
1002
+ // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
1003
+ // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
1004
+ // // match against a path regexp
1005
+ // app.contextMatchesOptions(context, /path/); //=> true
1006
+ // app.contextMatchesOptions(context, /^path/); //=> false
1007
+ // // match only a verb
1008
+ // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
1009
+ // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
1010
+ // // match all except a verb
1011
+ // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
1012
+ // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
1013
+ // // match all except a path
1014
+ // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
1015
+ // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
1016
+ //
1017
+ contextMatchesOptions: function(context, match_options, positive) {
1018
+ // empty options always match
1019
+ var options = match_options;
1020
+ if (typeof options === 'undefined' || options == {}) {
1021
+ return true;
1022
+ }
1023
+ if (typeof positive === 'undefined') {
1024
+ positive = true;
1025
+ }
1026
+ // normalize options
1027
+ if (typeof options === 'string' || _isFunction(options.test)) {
1028
+ options = {path: options};
1029
+ }
1030
+ if (options.only) {
1031
+ return this.contextMatchesOptions(context, options.only, true);
1032
+ } else if (options.except) {
1033
+ return this.contextMatchesOptions(context, options.except, false);
1034
+ }
1035
+ var path_matched = true, verb_matched = true;
1036
+ if (options.path) {
1037
+ // wierd regexp test
1038
+ if (_isFunction(options.path.test)) {
1039
+ path_matched = options.path.test(context.path);
1040
+ } else {
1041
+ path_matched = (options.path.toString() === context.path);
1042
+ }
1043
+ }
1044
+ if (options.verb) {
1045
+ verb_matched = options.verb === context.verb;
1046
+ }
1047
+ return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
1048
+ },
1049
+
1050
+
1051
+ // Delegates to the `location_proxy` to get the current location.
1052
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1053
+ getLocation: function() {
1054
+ return this.location_proxy.getLocation();
1055
+ },
1056
+
1057
+ // Delegates to the `location_proxy` to set the current location.
1058
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1059
+ //
1060
+ // ### Arguments
1061
+ //
1062
+ // * `new_location` A new location string (e.g. '#/')
1063
+ //
1064
+ setLocation: function(new_location) {
1065
+ return this.location_proxy.setLocation(new_location);
1066
+ },
1067
+
1068
+ // Swaps the content of `$element()` with `content`
1069
+ // You can override this method to provide an alternate swap behavior
1070
+ // for `EventContext.partial()`.
1071
+ //
1072
+ // ### Example
1073
+ //
1074
+ // var app = $.sammy(function() {
1075
+ //
1076
+ // // implements a 'fade out'/'fade in'
1077
+ // this.swap = function(content) {
1078
+ // this.$element().hide('slow').html(content).show('slow');
1079
+ // }
1080
+ //
1081
+ // get('#/', function() {
1082
+ // this.partial('index.html.erb') // will fade out and in
1083
+ // });
1084
+ //
1085
+ // });
1086
+ //
1087
+ swap: function(content) {
1088
+ return this.$element().html(content);
1089
+ },
1090
+
1091
+ // This thows a '404 Not Found' error by invoking `error()`.
1092
+ // Override this method or `error()` to provide custom
1093
+ // 404 behavior (i.e redirecting to / or showing a warning)
1094
+ notFound: function(verb, path) {
1095
+ var ret = this.error(['404 Not Found', verb, path].join(' '));
1096
+ return (verb === 'get') ? ret : true;
1097
+ },
1098
+
1099
+ // The base error handler takes a string `message` and an `Error`
1100
+ // object. If `raise_errors` is set to `true` on the app level,
1101
+ // this will re-throw the error to the browser. Otherwise it will send the error
1102
+ // to `log()`. Override this method to provide custom error handling
1103
+ // e.g logging to a server side component or displaying some feedback to the
1104
+ // user.
1105
+ error: function(message, original_error) {
1106
+ if (!original_error) { original_error = new Error(); }
1107
+ original_error.message = [message, original_error.message].join(' ');
1108
+ this.trigger('error', {message: original_error.message, error: original_error});
1109
+ if (this.raise_errors) {
1110
+ throw(original_error);
1111
+ } else {
1112
+ this.log(original_error.message, original_error);
1113
+ }
1114
+ },
1115
+
1116
+ _checkLocation: function() {
1117
+ var location, returned;
1118
+ // get current location
1119
+ location = this.getLocation();
1120
+ // compare to see if hash has changed
1121
+ if (location != this.last_location) {
1122
+ // reset last location
1123
+ this.last_location = location;
1124
+ // lookup route for current hash
1125
+ returned = this.runRoute('get', location);
1126
+ }
1127
+ return returned;
1128
+ },
1129
+
1130
+ _checkFormSubmission: function(form) {
1131
+ var $form, path, verb, params, returned;
1132
+ this.trigger('check-form-submission', {form: form});
1133
+ $form = $(form);
1134
+ path = $form.attr('action');
1135
+ verb = $.trim($form.attr('method').toString().toLowerCase());
1136
+ if (!verb || verb == '') { verb = 'get'; }
1137
+ this.log('_checkFormSubmission', $form, path, verb);
1138
+ if (verb === 'get') {
1139
+ this.setLocation(path + '?' + $form.serialize());
1140
+ returned = false;
1141
+ } else {
1142
+ params = $.extend({}, this._parseFormParams($form));
1143
+ returned = this.runRoute(verb, path, params, form.get(0));
1144
+ };
1145
+ return (typeof returned == 'undefined') ? false : returned;
1146
+ },
1147
+
1148
+ _parseFormParams: function($form) {
1149
+ var params = {},
1150
+ form_fields = $form.serializeArray(),
1151
+ i;
1152
+ for (i = 0; i < form_fields.length; i++) {
1153
+ params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
1154
+ }
1155
+ return params;
1156
+ },
1157
+
1158
+ _parseQueryString: function(path) {
1159
+ var params = {}, parts, pairs, pair, i;
1160
+
1161
+ parts = path.match(QUERY_STRING_MATCHER);
1162
+ if (parts) {
1163
+ pairs = parts[1].split('&');
1164
+ for (i = 0; i < pairs.length; i++) {
1165
+ pair = pairs[i].split('=');
1166
+ params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1]));
1167
+ }
1168
+ }
1169
+ return params;
1170
+ },
1171
+
1172
+ _parseParamPair: function(params, key, value) {
1173
+ if (params[key]) {
1174
+ if (_isArray(params[key])) {
1175
+ params[key].push(value);
1176
+ } else {
1177
+ params[key] = [params[key], value];
1178
+ }
1179
+ } else {
1180
+ params[key] = value;
1181
+ }
1182
+ return params;
1183
+ },
1184
+
1185
+ _listen: function(name, callback) {
1186
+ return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
1187
+ },
1188
+
1189
+ _unlisten: function(name, callback) {
1190
+ return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
1191
+ }
1192
+
1193
+ });
1194
+
1195
+ // `Sammy.EventContext` objects are created every time a route is run or a
1196
+ // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
1197
+ // This within these callbacks the special methods of `EventContext` are available.
1198
+ //
1199
+ // ### Example
1200
+ //
1201
+ // $.sammy(function() { with(this) {
1202
+ // // The context here is this Sammy.Application
1203
+ // get('#/:name', function() { with(this) {
1204
+ // // The context here is a new Sammy.EventContext
1205
+ // if (params['name'] == 'sammy') {
1206
+ // partial('name.html.erb', {name: 'Sammy'});
1207
+ // } else {
1208
+ // redirect('#/somewhere-else')
1209
+ // }
1210
+ // }});
1211
+ // }});
1212
+ //
1213
+ // Initialize a new EventContext
1214
+ //
1215
+ // ### Arguments
1216
+ //
1217
+ // * `app` The `Sammy.Application` this event is called within.
1218
+ // * `verb` The verb invoked to run this context/route.
1219
+ // * `path` The string path invoked to run this context/route.
1220
+ // * `params` An Object of optional params to pass to the context. Is converted
1221
+ // to a `Sammy.Object`.
1222
+ // * `target` a DOM element that the event that holds this context originates
1223
+ // from. For post, put and del routes, this is the form element that triggered
1224
+ // the route.
1225
+ //
1226
+ Sammy.EventContext = function(app, verb, path, params, target) {
1227
+ this.app = app;
1228
+ this.verb = verb;
1229
+ this.path = path;
1230
+ this.params = new Sammy.Object(params);
1231
+ this.target = target;
1232
+ };
1233
+
1234
+ Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
1235
+
1236
+ // A shortcut to the app's `$element()`
1237
+ $element: function() {
1238
+ return this.app.$element();
1239
+ },
1240
+
1241
+ // Used for rendering remote templates or documents within the current application/DOM.
1242
+ // By default Sammy and `partial()` know nothing about how your templates
1243
+ // should be interpeted/rendered. This is easy to change, though. `partial()` looks
1244
+ // for a method in `EventContext` that matches the extension of the file you're
1245
+ // fetching (e.g. 'myfile.template' will look for a template() method, 'myfile.haml' => haml(), etc.)
1246
+ // If no matching render method is found it just takes the file contents as is.
1247
+ //
1248
+ // If you're templates have different (or no) extensions, and you want to render them all
1249
+ // through the same engine, you can set the default/fallback template engine on the app level
1250
+ // by setting `app.template_engine` to the name of the engine or a `function() {}`
1251
+ //
1252
+ // ### Caching
1253
+ //
1254
+ // If you use the `Sammy.Cache` plugin, remote requests will be automatically cached unless
1255
+ // you explicitly set `cache_partials` to `false`
1256
+ //
1257
+ // ### Example
1258
+ //
1259
+ // There are a couple different ways to use `partial()`:
1260
+ //
1261
+ // partial('doc.html');
1262
+ // //=> Replaces $element() with the contents of doc.html
1263
+ //
1264
+ // use(Sammy.Template);
1265
+ // //=> includes the template() method
1266
+ // partial('doc.template', {name: 'Sammy'});
1267
+ // //=> Replaces $element() with the contents of doc.template run through `template()`
1268
+ //
1269
+ // partial('doc.html', function(data) {
1270
+ // // data is the contents of the template.
1271
+ // $('.other-selector').html(data);
1272
+ // });
1273
+ //
1274
+ // ### Iteration/Arrays
1275
+ //
1276
+ // If the data object passed to `partial()` is an Array, `partial()`
1277
+ // will itterate over each element in data calling the callback with the
1278
+ // results of interpolation and the index of the element in the array.
1279
+ //
1280
+ // use(Sammy.Template);
1281
+ // // item.template => "<li>I'm an item named <%= name %></li>"
1282
+ // partial('item.template', [{name: "Item 1"}, {name: "Item 2"}])
1283
+ // //=> Replaces $element() with:
1284
+ // // <li>I'm an item named Item 1</li><li>I'm an item named Item 2</li>
1285
+ // partial('item.template', [{name: "Item 1"}, {name: "Item 2"}], function(rendered, i) {
1286
+ // rendered; //=> <li>I'm an item named Item 1</li> // for each element in the Array
1287
+ // i; // the 0 based index of the itteration
1288
+ // });
1289
+ //
1290
+ partial: function(path, data, callback) {
1291
+ var file_data,
1292
+ wrapped_callback,
1293
+ engine,
1294
+ data_array,
1295
+ cache_key = 'partial:' + path,
1296
+ context = this;
1297
+
1298
+ // engine setup
1299
+ if ((engine = path.match(/\.([^\.]+)$/))) { engine = engine[1]; }
1300
+ // set the engine to the default template engine if no match is found
1301
+ if ((!engine || !_isFunction(context[engine])) && this.app.template_engine) {
1302
+ engine = this.app.template_engine;
1303
+ }
1304
+ if (engine && !_isFunction(engine) && _isFunction(context[engine])) {
1305
+ engine = context[engine];
1306
+ }
1307
+ if (!callback && _isFunction(data)) {
1308
+ // callback is in the data position
1309
+ callback = data;
1310
+ data = {};
1311
+ }
1312
+ data_array = (_isArray(data) ? data : [data || {}]);
1313
+ wrapped_callback = function(response) {
1314
+ var new_content = response,
1315
+ all_content = "";
1316
+ $.each(data_array, function(i, idata) {
1317
+ if (_isFunction(engine)) {
1318
+ new_content = engine.apply(context, [response, idata]);
1319
+ }
1320
+ // collect the content
1321
+ all_content += new_content;
1322
+ // if callback exists call it for each iteration
1323
+ if (callback) {
1324
+ // return the result of the callback
1325
+ // (you can bail the loop by returning false)
1326
+ return callback.apply(context, [new_content, i]);
1327
+ }
1328
+ });
1329
+ if (!callback) { context.swap(all_content); }
1330
+ context.trigger('changed');
1331
+ };
1332
+ if (this.app.cache_partials && this.cache(cache_key)) {
1333
+ // try to load the template from the cache
1334
+ wrapped_callback.apply(context, [this.cache(cache_key)]);
1335
+ } else {
1336
+ // the template wasnt cached, we need to fetch it
1337
+ $.get(path, function(response) {
1338
+ if (context.app.cache_partials) { context.cache(cache_key, response); }
1339
+ wrapped_callback.apply(context, [response]);
1340
+ });
1341
+ }
1342
+ },
1343
+
1344
+ // Changes the location of the current window. If `to` begins with
1345
+ // '#' it only changes the document's hash. If passed more than 1 argument
1346
+ // redirect will join them together with forward slashes.
1347
+ //
1348
+ // ### Example
1349
+ //
1350
+ // redirect('#/other/route');
1351
+ // // equivilent to
1352
+ // redirect('#', 'other', 'route');
1353
+ //
1354
+ redirect: function() {
1355
+ var to, args = _makeArray(arguments),
1356
+ current_location = this.app.getLocation();
1357
+ if (args.length > 1) {
1358
+ args.unshift('/');
1359
+ to = this.join.apply(this, args);
1360
+ } else {
1361
+ to = args[0];
1362
+ }
1363
+ this.trigger('redirect', {to: to});
1364
+ this.app.last_location = this.path;
1365
+ this.app.setLocation(to);
1366
+ if (current_location == to) {
1367
+ this.app.trigger('location-changed');
1368
+ }
1369
+ },
1370
+
1371
+ // Triggers events on `app` within the current context.
1372
+ trigger: function(name, data) {
1373
+ if (typeof data == 'undefined') { data = {}; }
1374
+ if (!data.context) { data.context = this; }
1375
+ return this.app.trigger(name, data);
1376
+ },
1377
+
1378
+ // A shortcut to app's `eventNamespace()`
1379
+ eventNamespace: function() {
1380
+ return this.app.eventNamespace();
1381
+ },
1382
+
1383
+ // A shortcut to app's `swap()`
1384
+ swap: function(contents) {
1385
+ return this.app.swap(contents);
1386
+ },
1387
+
1388
+ // Raises a possible `notFound()` error for the current path.
1389
+ notFound: function() {
1390
+ return this.app.notFound(this.verb, this.path);
1391
+ },
1392
+
1393
+ // //=> Sammy.EventContext: get #/ {}
1394
+ toString: function() {
1395
+ return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
1396
+ }
1397
+
1398
+ });
1399
+
1400
+ // An alias to Sammy
1401
+ $.sammy = window.Sammy = Sammy;
1402
+
1403
+ })(jQuery);