h2ocube_rails_assets 0.0.9 → 0.0.10

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