-
Notifications
You must be signed in to change notification settings - Fork 6
/
application.js
663 lines (514 loc) · 18.5 KB
/
application.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
//
// This file is automatically generated. any changes will be lost
//
require("./views");
require("./states");
require("./routing");
(function() {
function visit(vertex, fn, visited, path) {
var name = vertex.name,
vertices = vertex.incoming,
names = vertex.incomingNames,
len = names.length,
i;
if (!visited) {
visited = {};
}
if (!path) {
path = [];
}
if (visited.hasOwnProperty(name)) {
return;
}
path.push(name);
visited[name] = true;
for (i = 0; i < len; i++) {
visit(vertices[names[i]], fn, visited, path);
}
fn(vertex, path);
path.pop();
}
function DAG() {
this.names = [];
this.vertices = {};
}
DAG.prototype.add = function(name) {
if (!name) { return; }
if (this.vertices.hasOwnProperty(name)) {
return this.vertices[name];
}
var vertex = {
name: name, incoming: {}, incomingNames: [], hasOutgoing: false, value: null
};
this.vertices[name] = vertex;
this.names.push(name);
return vertex;
};
DAG.prototype.map = function(name, value) {
this.add(name).value = value;
};
DAG.prototype.addEdge = function(fromName, toName) {
if (!fromName || !toName || fromName === toName) {
return;
}
var from = this.add(fromName), to = this.add(toName);
if (to.incoming.hasOwnProperty(fromName)) {
return;
}
function checkCycle(vertex, path) {
if (vertex.name === toName) {
throw new Error("cycle detected: " + toName + " <- " + path.join(" <- "));
}
}
visit(from, checkCycle);
from.hasOutgoing = true;
to.incoming[fromName] = from;
to.incomingNames.push(fromName);
};
DAG.prototype.topsort = function(fn) {
var visited = {},
vertices = this.vertices,
names = this.names,
len = names.length,
i, vertex;
for (i = 0; i < len; i++) {
vertex = vertices[names[i]];
if (!vertex.hasOutgoing) {
visit(vertex, fn, visited);
}
}
};
DAG.prototype.addEdges = function(name, value, before, after) {
var i;
this.map(name, value);
if (before) {
if (typeof before === 'string') {
this.addEdge(name, before);
} else {
for (i = 0; i < before.length; i++) {
this.addEdge(name, before[i]);
}
}
}
if (after) {
if (typeof after === 'string') {
this.addEdge(after, name);
} else {
for (i = 0; i < after.length; i++) {
this.addEdge(after[i], name);
}
}
}
};
Ember.DAG = DAG;
})();
(function() {
/**
@module ember
@submodule ember-application
*/
var get = Ember.get, set = Ember.set;
/**
An instance of `Ember.Application` is the starting point for every Ember.js
application. It helps to instantiate, initialize and coordinate the many
objects that make up your app.
Each Ember.js app has one and only one `Ember.Application` object. In fact, the very
first thing you should do in your application is create the instance:
```javascript
window.App = Ember.Application.create();
```
Typically, the application object is the only global variable. All other
classes in your app should be properties on the `Ember.Application` instance,
which highlights its first role: a global namespace.
For example, if you define a view class, it might look like this:
```javascript
App.MyView = Ember.View.extend();
```
After all of your classes are defined, call `App.initialize()` to start the
application.
Because `Ember.Application` inherits from `Ember.Namespace`, any classes
you create will have useful string representations when calling `toString()`;
see the `Ember.Namespace` documentation for more information.
While you can think of your `Ember.Application` as a container that holds the
other classes in your application, there are several other responsibilities
going on under-the-hood that you may want to understand.
### Event Delegation
Ember.js uses a technique called _event delegation_. This allows the framework
to set up a global, shared event listener instead of requiring each view to do
it manually. For example, instead of each view registering its own `mousedown`
listener on its associated element, Ember.js sets up a `mousedown` listener on
the `body`.
If a `mousedown` event occurs, Ember.js will look at the target of the event and
start walking up the DOM node tree, finding corresponding views and invoking their
`mouseDown` method as it goes.
`Ember.Application` has a number of default events that it listens for, as well
as a mapping from lowercase events to camel-cased view method names. For
example, the `keypress` event causes the `keyPress` method on the view to be
called, the `dblclick` event causes `doubleClick` to be called, and so on.
If there is a browser event that Ember.js does not listen for by default, you
can specify custom events and their corresponding view method names by setting
the application's `customEvents` property:
```javascript
App = Ember.Application.create({
customEvents: {
// add support for the loadedmetadata media
// player event
'loadedmetadata': "loadedMetadata"
}
});
```
By default, the application sets up these event listeners on the document body.
However, in cases where you are embedding an Ember.js application inside an
existing page, you may want it to set up the listeners on an element inside
the body.
For example, if only events inside a DOM element with the ID of `ember-app` should
be delegated, set your application's `rootElement` property:
```javascript
window.App = Ember.Application.create({
rootElement: '#ember-app'
});
```
The `rootElement` can be either a DOM element or a jQuery-compatible selector
string. Note that *views appended to the DOM outside the root element will not
receive events.* If you specify a custom root element, make sure you only append
views inside it!
To learn more about the advantages of event delegation and the Ember.js view layer,
and a list of the event listeners that are setup by default, visit the
[Ember.js View Layer guide](http://emberjs.com/guides/view_layer#toc_event-delegation).
### Dependency Injection
One thing you may have noticed while using Ember.js is that you define *classes*, not
*instances*. When your application loads, all of the instances are created for you.
Creating these instances is the responsibility of `Ember.Application`.
When the `Ember.Application` initializes, it will look for an `Ember.Router` class
defined on the applications's `Router` property, like this:
```javascript
App.Router = Ember.Router.extend({
// ...
});
```
If found, the router is instantiated and saved on the application's `router`
property (note the lowercase 'r'). While you should *not* reference this router
instance directly from your application code, having access to `App.router`
from the console can be useful during debugging.
After the router is created, the application loops through all of the
registered _injections_ and invokes them once for each property on the
`Ember.Application` object.
An injection is a function that is responsible for instantiating objects from
classes defined on the application. By default, the only injection registered
instantiates controllers and makes them available on the router.
For example, if you define a controller class:
```javascript
App.MyController = Ember.Controller.extend({
// ...
});
```
Your router will receive an instance of `App.MyController` saved on its
`myController` property.
Libraries on top of Ember.js can register additional injections. For example,
if your application is using Ember Data, it registers an injection that
instantiates `DS.Store`:
```javascript
Ember.Application.registerInjection({
name: 'store',
before: 'controllers',
injection: function(app, router, property) {
if (property === 'Store') {
set(router, 'store', app[property].create());
}
}
});
```
### Routing
In addition to creating your application's router, `Ember.Application` is also
responsible for telling the router when to start routing.
By default, the router will begin trying to translate the current URL into
application state once the browser emits the `DOMContentReady` event. If you
need to defer routing, you can call the application's `deferReadiness()` method.
Once routing can begin, call the `advanceReadiness()` method.
If there is any setup required before routing begins, you can implement a `ready()`
method on your app that will be invoked immediately before routing begins:
```javascript
window.App = Ember.Application.create({
ready: function() {
this.set('router.enableLogging', true);
}
});
To begin routing, you must have at a minimum a top-level controller and view.
You define these as `App.ApplicationController` and `App.ApplicationView`,
respectively. Your application will not work if you do not define these two
mandatory classes. For example:
```javascript
App.ApplicationView = Ember.View.extend({
templateName: 'application'
});
App.ApplicationController = Ember.Controller.extend();
```
@class Application
@namespace Ember
@extends Ember.Namespace
*/
Ember.Application = Ember.Namespace.extend(
/** @scope Ember.Application.prototype */{
/**
The root DOM element of the Application. This can be specified as an
element or a
[jQuery-compatible selector string](http://api.jquery.com/category/selectors/).
This is the element that will be passed to the Application's,
`eventDispatcher`, which sets up the listeners for event delegation. Every
view in your application should be a child of the element you specify here.
@property rootElement
@type DOMElement
@default 'body'
*/
rootElement: 'body',
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
The event dispatcher is created by the application at initialization time
and sets up event listeners on the DOM element described by the
application's `rootElement` property.
See the documentation for `Ember.EventDispatcher` for more information.
@property eventDispatcher
@type Ember.EventDispatcher
@default null
*/
eventDispatcher: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
If you would like additional events to be delegated to your
views, set your `Ember.Application`'s `customEvents` property
to a hash containing the DOM event name as the key and the
corresponding view method name as the value. For example:
App = Ember.Application.create({
customEvents: {
// add support for the loadedmetadata media
// player event
'loadedmetadata': "loadedMetadata"
}
});
@property customEvents
@type Object
@default null
*/
customEvents: null,
autoinit: !Ember.testing,
isInitialized: false,
init: function() {
if (!this.$) { this.$ = Ember.$; }
this._super();
this.createEventDispatcher();
// Start off the number of deferrals at 1. This will be
// decremented by the Application's own `initialize` method.
this._readinessDeferrals = 1;
this.waitForDOMContentLoaded();
if (this.autoinit) {
var self = this;
this.$().ready(function() {
if (self.isDestroyed || self.isInitialized) return;
self.initialize();
});
}
},
/** @private */
createEventDispatcher: function() {
var rootElement = get(this, 'rootElement'),
eventDispatcher = Ember.EventDispatcher.create({
rootElement: rootElement
});
set(this, 'eventDispatcher', eventDispatcher);
},
waitForDOMContentLoaded: function() {
this.deferReadiness();
var self = this;
this.$().ready(function() {
self.advanceReadiness();
});
},
deferReadiness: function() {
Ember.assert("You cannot defer readiness since the `ready()` hook has already been called.", this._readinessDeferrals > 0);
this._readinessDeferrals++;
},
advanceReadiness: function() {
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
Ember.run.once(this, this.didBecomeReady);
}
},
/**
Instantiate all controllers currently available on the namespace
and inject them onto a router.
Example:
App.PostsController = Ember.ArrayController.extend();
App.CommentsController = Ember.ArrayController.extend();
var router = Ember.Router.create({
...
});
App.initialize(router);
router.get('postsController') // <App.PostsController:ember1234>
router.get('commentsController') // <App.CommentsController:ember1235>
@method initialize
@param router {Ember.Router}
*/
initialize: function(router) {
Ember.assert("Application initialize may only be call once", !this.isInitialized);
Ember.assert("Application not destroyed", !this.isDestroyed);
router = this.setupRouter(router);
this.runInjections(router);
Ember.runLoadHooks('application', this);
this.isInitialized = true;
// At this point, any injections or load hooks that would have wanted
// to defer readiness have fired.
this.advanceReadiness();
return this;
},
/** @private */
runInjections: function(router) {
var injections = get(this.constructor, 'injections'),
graph = new Ember.DAG(),
namespace = this,
properties, i, injection;
for (i=0; i<injections.length; i++) {
injection = injections[i];
graph.addEdges(injection.name, injection.injection, injection.before, injection.after);
}
graph.topsort(function (vertex) {
var injection = vertex.value,
properties = Ember.A(Ember.keys(namespace));
properties.forEach(function(property) {
injection(namespace, router, property);
});
});
},
/** @private */
setupRouter: function(router) {
if (!router && Ember.Router.detect(this.Router)) {
router = this.Router.create();
this._createdRouter = router;
}
if (router) {
set(this, 'router', router);
// By default, the router's namespace is the current application.
//
// This allows it to find model classes when a state has a
// route like `/posts/:post_id`. In that case, it would first
// convert `post_id` into `Post`, and then look it up on its
// namespace.
set(router, 'namespace', this);
}
return router;
},
/** @private */
didBecomeReady: function() {
var eventDispatcher = get(this, 'eventDispatcher'),
customEvents = get(this, 'customEvents'),
router;
eventDispatcher.setup(customEvents);
this.ready();
router = get(this, 'router');
this.createApplicationView(router);
if (router && router instanceof Ember.Router) {
this.startRouting(router);
}
},
createApplicationView: function (router) {
var rootElement = get(this, 'rootElement'),
applicationViewOptions = {},
applicationViewClass = this.ApplicationView,
applicationTemplate = Ember.TEMPLATES.application,
applicationController, applicationView;
// don't do anything unless there is an ApplicationView or application template
if (!applicationViewClass && !applicationTemplate) return;
if (router) {
applicationController = get(router, 'applicationController');
if (applicationController) {
applicationViewOptions.controller = applicationController;
}
}
if (applicationTemplate) {
applicationViewOptions.template = applicationTemplate;
}
if (!applicationViewClass) {
applicationViewClass = Ember.View;
}
applicationView = applicationViewClass.create(applicationViewOptions);
this._createdApplicationView = applicationView;
if (router) {
set(router, 'applicationView', applicationView);
}
applicationView.appendTo(rootElement);
},
/**
@private
If the application has a router, use it to route to the current URL, and
trigger a new call to `route` whenever the URL changes.
@method startRouting
@property router {Ember.Router}
*/
startRouting: function(router) {
var location = get(router, 'location');
Ember.assert("You must have an application template or ApplicationView defined on your application", get(router, 'applicationView') );
Ember.assert("You must have an ApplicationController defined on your application", get(router, 'applicationController') );
router.route(location.getURL());
location.onUpdateURL(function(url) {
router.route(url);
});
},
/**
Called when the Application has become ready.
The call will be delayed until the DOM has become ready.
@event ready
*/
ready: Ember.K,
willDestroy: function() {
get(this, 'eventDispatcher').destroy();
if (this._createdRouter) { this._createdRouter.destroy(); }
if (this._createdApplicationView) { this._createdApplicationView.destroy(); }
},
registerInjection: function(options) {
this.constructor.registerInjection(options);
}
});
Ember.Application.reopenClass({
concatenatedProperties: ['injections'],
injections: Ember.A(),
registerInjection: function(injection) {
var injections = get(this, 'injections');
Ember.assert("The injection '" + injection.name + "' has already been registered", !injections.findProperty('name', injection.name));
Ember.assert("An injection cannot be registered with both a before and an after", !(injection.before && injection.after));
Ember.assert("An injection cannot be registered without an injection function", Ember.canInvoke(injection, 'injection'));
injections.push(injection);
}
});
Ember.Application.registerInjection({
name: 'controllers',
injection: function(app, router, property) {
if (!router) { return; }
if (!/^[A-Z].*Controller$/.test(property)) { return; }
var name = property.charAt(0).toLowerCase() + property.substr(1),
controllerClass = app[property], controller;
if(!Ember.Object.detect(controllerClass)){ return; }
controller = app[property].create();
router.set(name, controller);
controller.setProperties({
target: router,
controllers: router,
namespace: app
});
}
});
Ember.runLoadHooks('Ember.Application', Ember.Application);
})();
(function() {
})();
(function() {
/**
Ember Application
@module ember
@submodule ember-application
@requires ember-views, ember-states, ember-routing
*/
})();