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