h2ocube_rails_assets 0.0.15 → 0.0.16

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