forked from olivernn/davis.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1834 lines (1667 loc) · 56 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Davis - http://davisjs.com - JavaScript Routing - 0.9.4
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
;
/**
* Convinience method for instantiating a new Davis app and configuring it to use the passed
* routes and subscriptions.
*
* @param {Function} config A function that will be run with a newly created Davis.App as its context,
* should be used to set up app routes, subscriptions and settings etc.
* @namespace
* @returns {Davis.App}
*/
Davis = function (config) {
var app = new Davis.App
config && config.call(app)
Davis.$(function () { app.start() })
return app
};
module.exports = Davis; //!Compenent Support
/**
* Stores the DOM library that Davis will use. Can be overriden to use libraries other than jQuery.
*/
if (window.jQuery) {
Davis.$ = jQuery
} else {
Davis.$ = require('jquery'); //!Compenent Support
};
/**
* Checks whether Davis is supported in the current browser
*
* @returns {Boolean}
*/
Davis.supported = function () {
return (typeof window.history.pushState == 'function')
}
/*!
* A function that does nothing, used as a default param for any callbacks.
*
* @private
* @returns {Function}
*/
Davis.noop = function () {}
/**
* Method to extend the Davis library with an extension.
*
* An extension is just a function that will modify the Davis framework in some way,
* for example changing how the routing works or adjusting where Davis thinks it is supported.
*
* Example:
* Davis.extend(Davis.hashBasedRouting)
*
* @param {Function} extension the function that will extend Davis
*
*/
Davis.extend = function (extension) {
extension(Davis)
}
/*!
* the version
*/
Davis.version = "0.9.4";/*!
* Davis - utils
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
/*!
* A module that provides wrappers around modern JavaScript so that native implementations are used
* whereever possible and JavaScript implementations are used in those browsers that do not natively
* support them.
*/
Davis.utils = (function () {
/*!
* A wrapper around native Array.prototype.every.
*
* Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.every.
* For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
*
* @private
* @param {array} the array to loop through
* @param {fn} the function to that performs the every check
* @param {thisp} an optional param that will be set as fn's this value
* @returns {Array}
*/
if (Array.prototype.every) {
var every = function (array, fn) {
return array.every(fn, arguments[2])
}
} else {
var every = function (array, fn) {
if (array === void 0 || array === null) throw new TypeError();
var t = Object(array);
var len = t.length >>> 0;
if (typeof fn !== "function") throw new TypeError();
var thisp = arguments[2];
for (var i = 0; i < len; i++) {
if (i in t && !fn.call(thisp, t[i], i, t)) return false;
}
return true;
}
};
/*!
* A wrapper around native Array.prototype.forEach.
*
* Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.forEach.
* For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
*
* @private
* @param {array} the array to loop through
* @param {fn} the function to apply to every element of the array
* @param {thisp} an optional param that will be set as fn's this value
* @returns {Array}
*/
if (Array.prototype.forEach) {
var forEach = function (array, fn) {
return array.forEach(fn, arguments[2])
}
} else {
var forEach = function (array, fn) {
if (array === void 0 || array === null) throw new TypeError();
var t = Object(array);
var len = t.length >>> 0;
if (typeof fn !== "function") throw new TypeError();
var thisp = arguments[2];
for (var i = 0; i < len; i++) {
if (i in t) fn.call(thisp, t[i], i, t);
}
};
};
/*!
* A wrapper around native Array.prototype.filter.
* Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.filter.
* For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
*
* @private
* @param {array} the array to filter
* @param {fn} the function to do the filtering
* @param {thisp} an optional param that will be set as fn's this value
* @returns {Array}
*/
if (Array.prototype.filter) {
var filter = function (array, fn) {
return array.filter(fn, arguments[2])
}
} else {
var filter = function(array, fn) {
if (array === void 0 || array === null) throw new TypeError();
var t = Object(array);
var len = t.length >>> 0;
if (typeof fn !== "function") throw new TypeError();
var res = [];
var thisp = arguments[2];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fn mutates this
if (fn.call(thisp, val, i, t)) res.push(val);
}
}
return res;
};
};
/*!
* A wrapper around native Array.prototype.map.
* Falls back to a pure JavaScript implementation in browsers that do not support Array.prototype.map.
* For more details see the full docs on MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
*
* @private
* @param {array} the array to map
* @param {fn} the function to do the mapping
* @param {thisp} an optional param that will be set as fn's this value
* @returns {Array}
*/
if (Array.prototype.map) {
var map = function (array, fn) {
return array.map(fn, arguments[2])
}
} else {
var map = function(array, fn) {
if (array === void 0 || array === null)
throw new TypeError();
var t = Object(array);
var len = t.length >>> 0;
if (typeof fn !== "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[2];
for (var i = 0; i < len; i++) {
if (i in t)
res[i] = fn.call(thisp, t[i], i, t);
}
return res;
};
};
/*!
* A convinience function for converting arguments to a proper array
*
* @private
* @param {args} a functions arguments
* @param {start} an integer at which to start converting the arguments to an array
* @returns {Array}
*/
var toArray = function (args, start) {
var start = start || 0
return Array.prototype.slice.call(args, start)
}
/*!
* Exposing the public interface to the Utils module
* @private
*/
return {
every: every,
forEach: forEach,
filter: filter,
toArray: toArray,
map: map
}
})()
/*!
* Davis - listener
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
/**
* A module to bind to link clicks and form submits and turn what would normally be http requests
* into instances of Davis.Request. These request objects are then pushed onto the history stack
* using the Davis.history module.
*
* This module uses Davis.$, which by defualt is jQuery for its event binding and event object normalization.
* To use Davis with any, or no, JavaScript framework be sure to provide support for all the methods called
* on Davis.$.
*
* @module
*/
Davis.listener = function () {
/*!
* Methods to check whether an element has an href or action that is local to this page
* @private
*/
var originChecks = {
A: function (elem) {
return elem.host !== window.location.host || elem.protocol !== window.location.protocol
},
FORM: function (elem) {
var a = document.createElement('a')
a.href = elem.action
return this.A(a)
}
}
/*!
* Checks whether the target of a click or submit event has an href or action that is local to the
* current page. Only links or targets with local hrefs or actions will be handled by davis, all
* others will be ignored.
* @private
*/
var differentOrigin = function (elem) {
if (!originChecks[elem.nodeName.toUpperCase()]) return true // the elem is neither a link or a form
return originChecks[elem.nodeName.toUpperCase()](elem)
}
/*!
* A handler that creates a new Davis.Request and pushes it onto the history stack using Davis.history.
*
* @param {Function} targetExtractor a function that will be called with the event target jQuery object and should return an object with path, title and method.
* @private
*/
var handler = function (targetExtractor) {
return function (event) {
if (differentOrigin(this)) return true
var request = new Davis.Request (targetExtractor.call(Davis.$(this)));
Davis.location.assign(request)
event.stopPropagation()
event.preventDefault()
return false;
};
};
/*!
* A handler specialized for click events. Gets the request details from a link elem
* @private
*/
var clickHandler = handler(function () {
var self = this
return {
method: 'get',
fullPath: this.attr('href'),
title: this.attr('title'),
delegateToServer: function () {
window.location = self.attr('href')
}
};
});
/*!
* Decodes the url, including + characters.
* @private
*/
var decodeUrl = function (str) {
return decodeURIComponent(str.replace(/\+/g, '%20'))
};
/*!
* A handler specialized for submit events. Gets the request details from a form elem
* @private
*/
var submitHandler = handler(function () {
var self = this
return {
method: this.attr('method'),
fullPath: decodeUrl(this.serialize() ? [this.attr('action'), this.serialize()].join("?") : this.attr('action')),
title: this.attr('title'),
delegateToServer: function () {
self.submit()
}
};
});
/**
* Binds to both link clicks and form submits using jQuery's deleagate.
*
* Will catch all current and future links and forms. Uses the apps settings for the selector to use for links and forms
*
* @see Davis.App.settings
* @memberOf listener
*/
this.listen = function () {
Davis.$(document).delegate(this.settings.formSelector, 'submit', submitHandler)
Davis.$(document).delegate(this.settings.linkSelector, 'click', clickHandler)
}
/**
* Unbinds all click and submit handlers that were attatched with listen.
*
* Will efectivley stop the current app from processing any requests and all links and forms will have their default
* behaviour restored.
*
* @see Davis.App.settings
* @memberOf listener
*/
this.unlisten = function () {
Davis.$(document).undelegate(this.settings.linkSelector, 'click', clickHandler)
Davis.$(document).undelegate(this.settings.formSelector, 'submit', submitHandler)
}
}
/*!
* Davis - event
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
/**
* A plugin that adds basic event capabilities to a Davis app, it is included by default.
*
* @module
*/
Davis.event = function () {
/*!
* callback storage
*/
var callbacks = {}
/**
* Binds a callback to a named event.
*
* The following events are triggered internally by Davis and can be bound to
*
* * start : Triggered when the application is started
* * lookupRoute : Triggered before looking up a route. The request being looked up is passed as an argument
* * runRoute : Triggered before running a route. The request and route being run are passed as arguments
* * routeNotFound : Triggered if no route for the current request can be found. The current request is passed as an arugment
* * requestHalted : Triggered when a before filter halts the current request. The current request is passed as an argument
* * unsupported : Triggered when starting a Davis app in a browser that doesn't support html5 pushState
*
* Example
*
* app.bind('runRoute', function () {
* console.log('about to run a route')
* })
*
* @param {String} event event name
* @param {Function} fn callback
* @memberOf event
*/
this.bind = function (event, fn) {
(callbacks[event] = callbacks[event] || []).push(fn);
return this;
};
/**
* Triggers an event with the given arguments.
*
* @param {String} event event name
* @param {Mixed} ...
* @memberOf event
*/
this.trigger = function (event) {
var args = Davis.utils.toArray(arguments, 1),
handlers = callbacks[event];
if (!handlers) return this
for (var i = 0, len = handlers.length; i < len; ++i) {
handlers[i].apply(this, args)
}
return this;
};
}
/*!
* Davis - logger
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
/**
* A plugin for enhancing the standard logging available through the console object.
* Automatically included in all Davis apps.
*
* Generates log messages of varying severity in the format
*
* `[Sun Jan 23 2011 16:15:21 GMT+0000 (GMT)] <message>`
*
* @module
*/
Davis.logger = function () {
/*!
* Generating the timestamp portion of the log message
* @private
*/
function timestamp(){
return "[" + Date() + "]";
}
/*!
* Pushing the timestamp onto the front of the arguments to log
* @private
*/
function prepArgs(args) {
var a = Davis.utils.toArray(args)
a.unshift(timestamp())
return a.join(' ');
}
var logType = function (logLevel) {
return function () {
if (window.console) console[logLevel](prepArgs(arguments));
}
}
/**
* Prints an error message to the console if the console is available.
*
* @params {String} All arguments are combined and logged to the console.
* @memberOf logger
*/
var error = logType('error')
/**
* Prints an info message to the console if the console is available.
*
* @params {String} All arguments are combined and logged to the console.
* @memberOf logger
*/
var info = logType('info')
/**
* Prints a warning message to the console if the console is available.
*
* @params {String} All arguments are combined and logged to the console.
* @memberOf logger
*/
var warn = logType('warn')
/*!
* Exposes the public methods of the module
* @private
*/
this.logger = {
error: error,
info: info,
warn: warn
}
}/*!
* Davis - Route
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
Davis.Route = (function () {
var pathNameRegex = /:([\w\d]+)/g;
var pathNameReplacement = "([^\/]+)";
var splatNameRegex = /\*([\w\d]+)/g;
var splatNameReplacement = "(.*)";
var nameRegex = /[:|\*]([\w\d]+)/g
/**
* Davis.Routes are the main part of a Davis application. They consist of an HTTP method, a path
* and a callback function. When a link or a form that Davis has bound to are clicked or submitted
* a request is pushed on the history stack and a route that matches the path and method of the
* generated request is run.
*
* The path for the route can consist of placeholders for attributes, these will then be available
* on the request. Simple variables should be prefixed with a colan, and for splat style params use
* an asterisk.
*
* Inside the callback function 'this' is bound to the request.
*
* Example:
*
* var route = new Davis.Route ('get', '/foo/:id', function (req) {
* var id = req.params['id']
* // do something interesting!
* })
*
* var route = new Davis.Route ('get', '/foo/*splat', function (req) {
* var id = req.params['splat']
* // splat will contain everything after the /foo/ in the path.
* })
*
* You can include any number of route level 'middleware' when defining routes. These middlewares are
* run in order and need to explicitly call the next handler in the stack. Using route middleware allows
* you to share common logic between routes and is also a good place to load any data or do any async calls
* keeping your main handler simple and focused.
*
* Example:
*
* var loadUser = function (req, next) {
* $.get('/users/current', function (user) {
* req.user = user
* next(req)
* })
* }
*
* var route = new Davis.Route ('get', '/foo/:id', loadUser, function (req) {
* renderUser(req.user)
* })
*
* @constructor
* @param {String} method This should be one of either 'get', 'post', 'put', 'delete', 'before', 'after' or 'state'
* @param {String} path This string can contain place holders for variables, e.g. '/user/:id' or '/user/*splat'
* @param {Function} callback One or more callbacks that will be called in order when a request matching both the path and method is triggered.
*/
var Route = function (method, path, handlers) {
var convertPathToRegExp = function () {
if (!(path instanceof RegExp)) {
var str = path
.replace(pathNameRegex, pathNameReplacement)
.replace(splatNameRegex, splatNameReplacement);
// Most browsers will reset this to zero after a replace call. IE will
// set it to the index of the last matched character.
path.lastIndex = 0;
return new RegExp("^" + str + "$", "gi");
} else {
return path;
};
};
var convertMethodToRegExp = function () {
if (!(method instanceof RegExp)) {
return new RegExp("^" + method + "$", "i");
} else {
return method
};
}
var capturePathParamNames = function () {
var names = [], a;
while ((a = nameRegex.exec(path))) names.push(a[1]);
return names;
};
this.paramNames = capturePathParamNames();
this.path = convertPathToRegExp();
this.method = convertMethodToRegExp();
if (typeof handlers === 'function') {
this.handlers = [handlers]
} else {
this.handlers = handlers;
}
}
/**
* Tests whether or not a route matches a particular request.
*
* Example:
*
* route.match('get', '/foo/12')
*
* @param {String} method the method to match against
* @param {String} path the path to match against
* @returns {Boolean}
*/
Route.prototype.match = function (method, path) {
this.reset();
return (this.method.test(method)) && (this.path.test(path))
}
/**
* Resets the RegExps for method and path
*/
Route.prototype.reset = function () {
this.method.lastIndex = 0;
this.path.lastIndex = 0;
}
/**
* Runs the callback associated with a particular route against the passed request.
*
* Any named params in the request path are extracted, as per the routes path, and
* added onto the requests params object.
*
* Example:
*
* route.run(request)
*
* @params {Davis.Request} request
* @returns {Object} whatever the routes callback returns
*/
Route.prototype.run = function (request) {
this.reset();
var matches = this.path.exec(request.path);
if (matches) {
matches.shift();
for (var i=0; i < matches.length; i++) {
request.params[this.paramNames[i]] = matches[i];
};
};
var handlers = Davis.utils.map(this.handlers, function (handler, i) {
return function (req) {
return handler.call(req, req, handlers[i+1])
}
})
return handlers[0](request)
}
/**
* Converts the route to a string representation of itself by combining the method and path
* attributes.
*
* @returns {String} string representation of the route
*/
Route.prototype.toString = function () {
return [this.method, this.path].join(' ');
}
/*!
* exposing the constructor
* @private
*/
return Route;
})()
/*!
* Davis - router
* Copyright (C) 2011 Oliver Nightingale
* MIT Licensed
*/
/**
* A decorator that adds convinience methods to a Davis.App for easily creating instances
* of Davis.Route and looking up routes for a particular request.
*
* Provides get, post put and delete method shortcuts for creating instances of Davis.Routes
* with the corresponding method. This allows simple REST styled routing for a client side
* JavaScript application.
*
* ### Example
*
* app.get('/foo/:id', function (req) {
* // get the foo with id = req.params['id']
* })
*
* app.post('/foo', function (req) {
* // create a new instance of foo with req.params
* })
*
* app.put('/foo/:id', function (req) {
* // update the instance of foo with id = req.params['id']
* })
*
* app.del('/foo/:id', function (req) {
* // delete the instance of foo with id = req.params['id']
* })
*
* As well as providing convinience methods for creating instances of Davis.Routes the router
* also provides methods for creating special instances of routes called filters. Before filters
* run before any matching route is run, and after filters run after any matched route has run.
* A before filter can return false to halt the running of any matched routes or other before filters.
*
* A filter can take an optional path to match on, or without a path will match every request.
*
* ### Example
*
* app.before('/foo/:id', function (req) {
* // will only run before request matching '/foo/:id'
* })
*
* app.before(function (req) {
* // will run before all routes
* })
*
* app.after('/foo/:id', function (req) {
* // will only run after routes matching '/foo/:id'
* })
*
* app.after(function (req) {
* // will run after all routes
* })
*
* Another special kind of route, called state routes, are also generated using the router. State routes
* are for requests that will not change the current page location. Instead the page location will remain
* the same but the current state of the page has changed. This allows for states which the server will not
* be expected to know about and support.
*
* ### Example
*
* app.state('/foo/:id', function (req) {
* // will run when the app transitions into the '/foo/:id' state.
* })
*
* Using the `trans` method an app can transition to these kind of states without changing the url location.
*
* For convinience routes can be defined within a common base scope, this is useful for keeping your route
* definitions simpler and DRYer. A scope can either cover the whole app, or just a subset of the routes.
*
* ### Example
*
* app.scope('/foo', function () {
* this.get('/:id', function () {
* // will run for routes that match '/foo/:id'
* })
* })
*
* @module
*/
Davis.router = function () {
/**
* Low level method for adding routes to your application.
*
* If called with just a method will return a partially applied function that can create routes with
* that method. This is used internally to provide shortcuts for get, post, put, delete and state
* routes.
*
* You normally want to use the higher level methods such as get and post, but this can be useful for extending
* Davis to work with other kinds of requests.
*
* Example:
*
* app.route('get', '/foo', function (req) {
* // will run when a get request is made to '/foo'
* })
*
* app.patch = app.route('patch') // will return a function that can be used to handle requests with method of patch.
* app.patch('/bar', function (req) {
* // will run when a patch request is made to '/bar'
* })
*
* @param {String} method The method for this route.
* @param {String} path The path for this route.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route.
* @returns {Davis.Route} the route that has just been created and added to the route list.
* @memberOf router
*/
this.route = function (method, path) {
var createRoute = function (path) {
var handlers = Davis.utils.toArray(arguments, 1),
scope = scopePaths.join(''),
fullPath, route
(typeof path == 'string') ? fullPath = scope + path : fullPath = path
route = new Davis.Route (method, fullPath, handlers)
routeCollection.push(route)
return route
}
return (arguments.length == 1) ? createRoute : createRoute.apply(this, Davis.utils.toArray(arguments, 1))
}
/**
* A convinience wrapper around `app.route` for creating get routes.
*
* @param {String} path The path for this route.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route.
* @returns {Davis.Route} the route that has just been created and added to the route list.
* @see Davis.router.route
* @memberOf router
*/
this.get = this.route('get')
/**
* A convinience wrapper around `app.route` for creating post routes.
*
* @param {String} path The path for this route.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route.
* @returns {Davis.Route} the route that has just been created and added to the route list.
* @see Davis.router.route
* @memberOf router
*/
this.post = this.route('post')
/**
* A convinience wrapper around `app.route` for creating put routes.
*
* @param {String} path The path for this route.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route.
* @returns {Davis.Route} the route that has just been created and added to the route list.
* @see Davis.router.route
* @memberOf router
*/
this.put = this.route('put')
/**
* A convinience wrapper around `app.route` for creating delete routes.
*
* delete is a reserved word in javascript so use the `del` method when creating a Davis.Route with a method of delete.
*
* @param {String} path The path for this route.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route.
* @returns {Davis.Route} the route that has just been created and added to the route list.
* @see Davis.router.route
* @memberOf router
*/
this.del = this.route('delete')
/**
* Adds a state route into the apps route collection.
*
* These special kind of routes are not triggered by clicking links or submitting forms, instead they
* are triggered manually by calling `trans`.
*
* Routes added using the state method act in the same way as other routes except that they generate
* a route that is listening for requests that will not change the page location.
*
* Example:
*
* app.state('/foo/:id', function (req) {
* // will run when the app transitions into the '/foo/:id' state.
* })
*
* @param {String} path The path for this route, this will never be seen in the url bar.
* @param {Function} handler The handler for this route, will be called with the request that triggered the route
* @memberOf router
*
*/
this.state = this.route('state');
/**
* Modifies the scope of the router.
*
* If you have many routes that share a common path prefix you can use scope to reduce repeating
* that path prefix.
*
* You can use `scope` in two ways, firstly you can set the scope for the whole app by calling scope
* before defining routes. You can also provide a function to the scope method, and the scope will
* only apply to those routes defined within this function. It is also possible to nest scopes within
* other scopes.
*
* Example
*
* // using scope with a function
* app.scope('/foo', function () {
* this.get('/bar', function (req) {
* // this route will have a path of '/foo/bar'
* })
* })
*
* // setting a global scope for the rest of the application
* app.scope('/bar')
*
* // using scope with a function
* app.scope('/foo', function () {
* this.scope('/bar', function () {
* this.get('/baz', function (req) {
* // this route will have a path of '/foo/bar/baz'
* })
* })
* })
*
* @memberOf router
* @param {String} path The prefix to use as the scope
* @param {Function} fn A function that will be executed with the router as its context and the path
* as a prefix
*
*/
this.scope = function (path, fn) {
scopePaths.push(path)
if (arguments.length == 1) return
fn.call(this, this)
scopePaths.pop()
}
/**
* Transitions the app into the state identified by the passed path parameter.
*
* This allows the app to enter states without changing the page path through a link click or form submit.
* If there are handlers registered for this state, added by the `state` method, they will be triggered.
*
* This method generates a request with a method of 'state', in all other ways this request is identical
* to those that are generated when clicking links etc.
*
* States transitioned to using this method will not be able to be revisited directly with a page load as
* there is no url that represents the state.
*
* An optional second parameter can be passed which will be available to any handlers in the requests
* params object.
*
* Example
*
* app.trans('/foo/1')
*
* app.trans('/foo/1', {
* "bar": "baz"
* })
*
*
* @param {String} path The path that represents this state. This will not be seen in the url bar.
* @param {Object} data Any additional data that should be sent with the request as params.
* @memberOf router
*/
this.trans = function (path, data) {
if (data) {
var fullPath = [path, decodeURIComponent(Davis.$.param(data))].join('?')
} else {
var fullPath = path
};
var req = new Davis.Request({
method: 'state',
fullPath: fullPath,
title: ''
})
Davis.location.assign(req)
}
/*!
* Generating convinience methods for creating filters using Davis.Routes and methods to
* lookup filters.
*/
this.filter = function (filterName) {
return function () {
var method = /.+/;
if (arguments.length == 1) {
var path = /.+/;
var handler = arguments[0];
} else if (arguments.length == 2) {
var path = scopePaths.join('') + arguments[0];
var handler = arguments[1];
};
var route = new Davis.Route (method, path, handler)
filterCollection[filterName].push(route);
return route
}
}