forked from Tabcorp/ember-states-shim-latest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathember-states.js
1528 lines (1250 loc) · 43.2 KB
/
ember-states.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Last commit: 17696b4 (2014-03-16 07:44:50 -0500)
(function() {
var define, requireModule;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requireModule = function(name) {
if (seen[name]) { return seen[name]; }
seen[name] = {};
var mod, deps, callback, reified , exports;
mod = registry[name];
if (!mod) {
throw new Error("Module '" + name + "' not found.");
}
deps = mod.deps;
callback = mod.callback;
reified = [];
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(deps[i]));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
};
})();
(function() {
var get = Ember.get, set = Ember.set;
/**
@module ember
@submodule ember-states
*/
/**
The State class allows you to define individual states within a finite state machine
inside your Ember application.
### How States Work
When you setup a finite state machine this means you are setting up a mechanism to precisely
manage the change within a system. You can control the various states or modes that your
application can be in at any given time. Additionally, you can manage what specific states
are allowed to transition to other states.
The state machine is in only one state at a time. This state is known as the current state.
It is possible to change from one state to another by a triggering event or condition.
This is called a transition.
Finite state machines are important because they allow the application developer to be
deterministic about the the sequence of events that can happen within a system. Some states
cannot be entered when the application is a given state.
For example:
A door that is in the `locked` state cannot be `opened` (you must transition to the `unlocked`
state first).
A door that is in the `open` state cannot be `locked` (you must transition to the `closed`
state first).
Each state instance has the following characteristics:
- Zero or more parent states
- A start state
- A name
- A path (a computed value that prefixes parent states and the complete hierarchy to itself )
A state is known as a "leafState" when it is the last item on the path and has no children
beneath it.
The isLeaf property returns a boolean.
Each state can emit the following transition events
- setup
- enter
- exit
A state object is ususally created in the context of a state manager.
```javascript
doorStateManager = Ember.StateManager.create({
locked: Ember.State.create(),
closed: Ember.State.create(),
unlocked: Ember.State.create(),
open: Ember.State.create()
});
```
@class State
@namespace Ember
@extends Ember.Object
@uses Ember.Evented
*/
Ember.State = Ember.Object.extend(Ember.Evented,
/** @scope Ember.State.prototype */{
/**
A reference to the parent state.
@property parentState
@type Ember.State
*/
parentState: null,
start: null,
/**
The name of this state.
@property name
@type String
*/
name: null,
/**
The full path to this state.
@property path
@type String
*/
path: Ember.computed(function() {
var parentPath = get(this, 'parentState.path'),
path = get(this, 'name');
if (parentPath) {
path = parentPath + '.' + path;
}
return path;
}),
/**
@private
Override the default event firing from `Ember.Evented` to
also call methods with the given name.
@method trigger
@param name
*/
trigger: function(name) {
if (this[name]) {
this[name].apply(this, [].slice.call(arguments, 1));
}
this._super.apply(this, arguments);
},
/**
Initialize Ember.State object
Sets childStates to Ember.NativeArray
Sets eventTransitions to empty object unless already defined.
Loops over properties of this state and ensures that any property that
is an instance of Ember.State is moved to `states` hash.
@method init
*/
init: function() {
var states = get(this, 'states');
set(this, 'childStates', Ember.A());
set(this, 'eventTransitions', get(this, 'eventTransitions') || {});
var name, value, transitionTarget;
// As a convenience, loop over the properties
// of this state and look for any that are other
// Ember.State instances or classes, and move them
// to the `states` hash. This avoids having to
// create an explicit separate hash.
if (!states) {
states = {};
for (name in this) {
if (name === "constructor") { continue; }
if (value = this[name]) {
if (transitionTarget = value.transitionTarget) {
this.eventTransitions[name] = transitionTarget;
}
this.setupChild(states, name, value);
}
}
set(this, 'states', states);
} else {
for (name in states) {
this.setupChild(states, name, states[name]);
}
}
// pathsCaches is a nested hash of the form:
// pathsCaches[stateManagerTypeGuid][path] == transitions_hash
set(this, 'pathsCaches', {});
},
/**
Sets a cached instance of the state. Ember.guidFor is used
to find the guid of the associated state manager. If a cache can be found
the state path is added to that cache, otherwise an empty JavaScript object
is created. And the state path is appended to that instead.
@method setPathsCache
@param stateManager
@param path
@param transitions
*/
setPathsCache: function(stateManager, path, transitions) {
var stateManagerTypeGuid = Ember.guidFor(stateManager.constructor),
pathsCaches = get(this, 'pathsCaches'),
pathsCacheForManager = pathsCaches[stateManagerTypeGuid] || {};
pathsCacheForManager[path] = transitions;
pathsCaches[stateManagerTypeGuid] = pathsCacheForManager;
},
/**
Returns a cached path for the state instance. Each state manager
has a GUID and this is used to look up a cached path if it has already
been created. If a cached path is not found an empty JavaScript object
is returned instead.
@method getPathsCache
@param stateManager
@param path
*/
getPathsCache: function(stateManager, path) {
var stateManagerTypeGuid = Ember.guidFor(stateManager.constructor),
pathsCaches = get(this, 'pathsCaches'),
pathsCacheForManager = pathsCaches[stateManagerTypeGuid] || {};
return pathsCacheForManager[path];
},
/**
@private
Create the child instance and ensure that it is an instance of Ember.State
@method setupChild
@param states
@param name
@param value
*/
setupChild: function(states, name, value) {
if (!value) { return false; }
var instance;
if (value instanceof Ember.State) {
set(value, 'name', name);
instance = value;
instance.container = this.container;
} else if (Ember.State.detect(value)) {
instance = value.create({
name: name,
container: this.container
});
}
if (instance instanceof Ember.State) {
set(instance, 'parentState', this);
get(this, 'childStates').pushObject(instance);
states[name] = instance;
return instance;
}
},
/**
@private
@method lookupEventTransition
@param name
*/
lookupEventTransition: function(name) {
var path, state = this;
while(state && !path) {
path = state.eventTransitions[name];
state = state.get('parentState');
}
return path;
},
/**
A Boolean value indicating whether the state is a leaf state
in the state hierarchy. This is `false` if the state has child
states; otherwise it is true.
@property isLeaf
@type Boolean
*/
isLeaf: Ember.computed(function() {
return !get(this, 'childStates').length;
}),
/**
A boolean value indicating whether the state takes a context.
By default we assume all states take contexts.
@property hasContext
@default true
*/
hasContext: true,
/**
This is the default transition event.
@event setup
@param {Ember.StateManager} manager
@param context
@see Ember.StateManager#transitionEvent
*/
setup: Ember.K,
/**
This event fires when the state is entered.
@event enter
@param {Ember.StateManager} manager
*/
enter: Ember.K,
/**
This event fires when the state is exited.
@event exit
@param {Ember.StateManager} manager
*/
exit: Ember.K
});
Ember.State.reopenClass({
/**
Creates an action function for transitioning to the named state while
preserving context.
The following example StateManagers are equivalent:
```javascript
aManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: Ember.State.transitionTo('stateTwo')
}),
stateTwo: Ember.State.create({})
})
bManager = Ember.StateManager.create({
stateOne: Ember.State.create({
changeToStateTwo: function(manager, context) {
manager.transitionTo('stateTwo', context)
}
}),
stateTwo: Ember.State.create({})
})
```
@method transitionTo
@static
@param {String} target
*/
transitionTo: function(target) {
var transitionFunction = function(stateManager, contextOrEvent) {
var contexts = [],
Event = Ember.$ && Ember.$.Event;
if (contextOrEvent && (Event && contextOrEvent instanceof Event)) {
if (contextOrEvent.hasOwnProperty('contexts')) {
contexts = contextOrEvent.contexts.slice();
}
}
else {
contexts = [].slice.call(arguments, 1);
}
contexts.unshift(target);
stateManager.transitionTo.apply(stateManager, contexts);
};
transitionFunction.transitionTarget = target;
return transitionFunction;
}
});
})();
(function() {
/**
@module ember
@submodule ember-states
*/
var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt;
var arrayForEach = Ember.ArrayPolyfills.forEach;
/**
A Transition takes the enter, exit and resolve states and normalizes
them:
* takes any passed in contexts into consideration
* adds in `initialState`s
@class Transition
@private
*/
var Transition = function(raw) {
this.enterStates = raw.enterStates.slice();
this.exitStates = raw.exitStates.slice();
this.resolveState = raw.resolveState;
this.finalState = raw.enterStates[raw.enterStates.length - 1] || raw.resolveState;
};
Transition.prototype = {
/**
Normalize the passed in enter, exit and resolve states.
This process also adds `finalState` and `contexts` to the Transition object.
@method normalize
@param {Ember.StateManager} manager the state manager running the transition
@param {Array} contexts a list of contexts passed into `transitionTo`
*/
normalize: function(manager, contexts) {
this.matchContextsToStates(contexts);
this.addInitialStates();
this.removeUnchangedContexts(manager);
return this;
},
/**
Match each of the contexts passed to `transitionTo` to a state.
This process may also require adding additional enter and exit
states if there are more contexts than enter states.
@method matchContextsToStates
@param {Array} contexts a list of contexts passed into `transitionTo`
*/
matchContextsToStates: function(contexts) {
var stateIdx = this.enterStates.length - 1,
matchedContexts = [],
state,
context;
// Next, we will match the passed in contexts to the states they
// represent.
//
// First, assign a context to each enter state in reverse order. If
// any contexts are left, add a parent state to the list of states
// to enter and exit, and assign a context to the parent state.
//
// If there are still contexts left when the state manager is
// reached, raise an exception.
//
// This allows the following:
//
// |- root
// | |- post
// | | |- comments
// | |- about (* current state)
//
// For `transitionTo('post.comments', post, post.get('comments')`,
// the first context (`post`) will be assigned to `root.post`, and
// the second context (`post.get('comments')`) will be assigned
// to `root.post.comments`.
//
// For the following:
//
// |- root
// | |- post
// | | |- index (* current state)
// | | |- comments
//
// For `transitionTo('post.comments', otherPost, otherPost.get('comments')`,
// the `<root.post>` state will be added to the list of enter and exit
// states because its context has changed.
while (contexts.length > 0) {
if (stateIdx >= 0) {
state = this.enterStates[stateIdx--];
} else {
if (this.enterStates.length) {
state = get(this.enterStates[0], 'parentState');
if (!state) { throw "Cannot match all contexts to states"; }
} else {
// If re-entering the current state with a context, the resolve
// state will be the current state.
state = this.resolveState;
}
this.enterStates.unshift(state);
this.exitStates.unshift(state);
}
// in routers, only states with dynamic segments have a context
if (get(state, 'hasContext')) {
context = contexts.pop();
} else {
context = null;
}
matchedContexts.unshift(context);
}
this.contexts = matchedContexts;
},
/**
Add any `initialState`s to the list of enter states.
@method addInitialStates
*/
addInitialStates: function() {
var finalState = this.finalState, initialState;
while(true) {
initialState = get(finalState, 'initialState') || 'start';
finalState = get(finalState, 'states.' + initialState);
if (!finalState) { break; }
this.finalState = finalState;
this.enterStates.push(finalState);
this.contexts.push(undefined);
}
},
/**
Remove any states that were added because the number of contexts
exceeded the number of explicit enter states, but the context has
not changed since the last time the state was entered.
@method removeUnchangedContexts
@param {Ember.StateManager} manager passed in to look up the last
context for a state
*/
removeUnchangedContexts: function(manager) {
// Start from the beginning of the enter states. If the state was added
// to the list during the context matching phase, make sure the context
// has actually changed since the last time the state was entered.
while (this.enterStates.length > 0) {
if (this.enterStates[0] !== this.exitStates[0]) { break; }
if (this.enterStates.length === this.contexts.length) {
if (manager.getStateMeta(this.enterStates[0], 'context') !== this.contexts[0]) { break; }
this.contexts.shift();
}
this.resolveState = this.enterStates.shift();
this.exitStates.shift();
}
}
};
/**
Sends the event to the currentState, if the event is not handled this method
will proceed to call the parentState recursively until it encounters an
event handler or reaches the top or root of the state path hierarchy.
@method sendRecursively
@param event
@param currentState
@param isUnhandledPass
*/
var sendRecursively = function(event, currentState, isUnhandledPass) {
var log = this.enableLogging,
eventName = isUnhandledPass ? 'unhandledEvent' : event,
action = currentState[eventName],
contexts, sendRecursiveArguments, actionArguments;
contexts = [].slice.call(arguments, 3);
// Test to see if the action is a method that
// can be invoked. Don't blindly check just for
// existence, because it is possible the state
// manager has a child state of the given name,
// and we should still raise an exception in that
// case.
if (typeof action === 'function') {
if (log) {
if (isUnhandledPass) {
Ember.Logger.log(fmt("STATEMANAGER: Unhandled event '%@' being sent to state %@.", [event, get(currentState, 'path')]));
} else {
Ember.Logger.log(fmt("STATEMANAGER: Sending event '%@' to state %@.", [event, get(currentState, 'path')]));
}
}
actionArguments = contexts;
if (isUnhandledPass) {
actionArguments.unshift(event);
}
actionArguments.unshift(this);
return action.apply(currentState, actionArguments);
} else {
var parentState = get(currentState, 'parentState');
if (parentState) {
sendRecursiveArguments = contexts;
sendRecursiveArguments.unshift(event, parentState, isUnhandledPass);
return sendRecursively.apply(this, sendRecursiveArguments);
} else if (!isUnhandledPass) {
return sendEvent.call(this, event, contexts, true);
}
}
};
/**
Send an event to the currentState.
@method sendEvent
@param eventName
@param sendRecursiveArguments
@param isUnhandledPass
*/
var sendEvent = function(eventName, sendRecursiveArguments, isUnhandledPass) {
sendRecursiveArguments.unshift(eventName, get(this, 'currentState'), isUnhandledPass);
return sendRecursively.apply(this, sendRecursiveArguments);
};
/**
StateManager is part of Ember's implementation of a finite state machine. A
StateManager instance manages a number of properties that are instances of
`Ember.State`,
tracks the current active state, and triggers callbacks when states have changed.
## Defining States
The states of StateManager can be declared in one of two ways. First, you can
define a `states` property that contains all the states:
```javascript
var managerA = Ember.StateManager.create({
states: {
stateOne: Ember.State.create(),
stateTwo: Ember.State.create()
}
});
managerA.get('states');
// {
// stateOne: Ember.State.create(),
// stateTwo: Ember.State.create()
// }
```
You can also add instances of `Ember.State` (or an `Ember.State` subclass)
directly as properties of a StateManager. These states will be collected into
the `states` property for you.
```javascript
var managerA = Ember.StateManager.create({
stateOne: Ember.State.create(),
stateTwo: Ember.State.create()
});
managerA.get('states');
// {
// stateOne: Ember.State.create(),
// stateTwo: Ember.State.create()
// }
```
## The Initial State
When created, a StateManager instance will immediately enter into the state
defined as its `start` property or the state referenced by name in its
`initialState` property:
```javascript
var managerA = Ember.StateManager.create({
start: Ember.State.create({})
});
managerA.get('currentState.name'); // 'start'
var managerB = Ember.StateManager.create({
initialState: 'beginHere',
beginHere: Ember.State.create({})
});
managerB.get('currentState.name'); // 'beginHere'
```
Because it is a property you may also provide a computed function if you wish
to derive an `initialState` programmatically:
```javascript
var managerC = Ember.StateManager.create({
initialState: function() {
if (someLogic) {
return 'active';
} else {
return 'passive';
}
}.property(),
active: Ember.State.create({}),
passive: Ember.State.create({})
});
```
## Moving Between States
A StateManager can have any number of `Ember.State` objects as properties
and can have a single one of these states as its current state.
Calling `transitionTo` transitions between states:
```javascript
var robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({}),
poweredUp: Ember.State.create({})
});
robotManager.get('currentState.name'); // 'poweredDown'
robotManager.transitionTo('poweredUp');
robotManager.get('currentState.name'); // 'poweredUp'
```
Before transitioning into a new state the existing `currentState` will have
its `exit` method called with the StateManager instance as its first argument
and an object representing the transition as its second argument.
After transitioning into a new state the new `currentState` will have its
`enter` method called with the StateManager instance as its first argument
and an object representing the transition as its second argument.
```javascript
var robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
exit: function(stateManager) {
console.log("exiting the poweredDown state")
}
}),
poweredUp: Ember.State.create({
enter: function(stateManager) {
console.log("entering the poweredUp state. Destroy all humans.")
}
})
});
robotManager.get('currentState.name'); // 'poweredDown'
robotManager.transitionTo('poweredUp');
// will log
// 'exiting the poweredDown state'
// 'entering the poweredUp state. Destroy all humans.'
```
Once a StateManager is already in a state, subsequent attempts to enter that
state will not trigger enter or exit method calls. Attempts to transition
into a state that the manager does not have will result in no changes in the
StateManager's current state:
```javascript
var robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
exit: function(stateManager) {
console.log("exiting the poweredDown state")
}
}),
poweredUp: Ember.State.create({
enter: function(stateManager) {
console.log("entering the poweredUp state. Destroy all humans.")
}
})
});
robotManager.get('currentState.name'); // 'poweredDown'
robotManager.transitionTo('poweredUp');
// will log
// 'exiting the poweredDown state'
// 'entering the poweredUp state. Destroy all humans.'
robotManager.transitionTo('poweredUp'); // no logging, no state change
robotManager.transitionTo('someUnknownState'); // silently fails
robotManager.get('currentState.name'); // 'poweredUp'
```
Each state property may itself contain properties that are instances of
`Ember.State`. The StateManager can transition to specific sub-states in a
series of transitionTo method calls or via a single transitionTo with the
full path to the specific state. The StateManager will also keep track of the
full path to its currentState
```javascript
var robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
charging: Ember.State.create(),
charged: Ember.State.create()
}),
poweredUp: Ember.State.create({
mobile: Ember.State.create(),
stationary: Ember.State.create()
})
});
robotManager.get('currentState.name'); // 'poweredDown'
robotManager.transitionTo('poweredUp');
robotManager.get('currentState.name'); // 'poweredUp'
robotManager.transitionTo('mobile');
robotManager.get('currentState.name'); // 'mobile'
// transition via a state path
robotManager.transitionTo('poweredDown.charging');
robotManager.get('currentState.name'); // 'charging'
robotManager.get('currentState.path'); // 'poweredDown.charging'
```
Enter transition methods will be called for each state and nested child state
in their hierarchical order. Exit methods will be called for each state and
its nested states in reverse hierarchical order.
Exit transitions for a parent state are not called when entering into one of
its child states, only when transitioning to a new section of possible states
in the hierarchy.
```javascript
var robotManager = Ember.StateManager.create({
initialState: 'poweredDown',
poweredDown: Ember.State.create({
enter: function() {},
exit: function() {
console.log("exited poweredDown state")
},
charging: Ember.State.create({
enter: function() {},
exit: function() {}
}),
charged: Ember.State.create({
enter: function() {
console.log("entered charged state")
},
exit: function() {
console.log("exited charged state")
}
})
}),
poweredUp: Ember.State.create({
enter: function() {
console.log("entered poweredUp state")
},
exit: function() {},
mobile: Ember.State.create({
enter: function() {
console.log("entered mobile state")
},
exit: function() {}
}),
stationary: Ember.State.create({
enter: function() {},
exit: function() {}
})
})
});
robotManager.get('currentState.path'); // 'poweredDown'
robotManager.transitionTo('charged');
// logs 'entered charged state'
// but does *not* log 'exited poweredDown state'
robotManager.get('currentState.name'); // 'charged
robotManager.transitionTo('poweredUp.mobile');
// logs
// 'exited charged state'
// 'exited poweredDown state'
// 'entered poweredUp state'
// 'entered mobile state'
```
During development you can set a StateManager's `enableLogging` property to
`true` to receive console messages of state transitions.
```javascript
var robotManager = Ember.StateManager.create({
enableLogging: true
});
```
## Managing currentState with Actions
To control which transitions are possible for a given state, and
appropriately handle external events, the StateManager can receive and
route action messages to its states via the `send` method. Calling to
`send` with an action name will begin searching for a method with the same
name starting at the current state and moving up through the parent states
in a state hierarchy until an appropriate method is found or the StateManager
instance itself is reached.
If an appropriately named method is found it will be called with the state
manager as the first argument and an optional `context` object as the second
argument.
```javascript
var managerA = Ember.StateManager.create({
initialState: 'stateOne.substateOne.subsubstateOne',
stateOne: Ember.State.create({
substateOne: Ember.State.create({
anAction: function(manager, context) {
console.log("an action was called")
},
subsubstateOne: Ember.State.create({})
})
})
});
managerA.get('currentState.name'); // 'subsubstateOne'
managerA.send('anAction');
// 'stateOne.substateOne.subsubstateOne' has no anAction method
// so the 'anAction' method of 'stateOne.substateOne' is called
// and logs "an action was called"
// with managerA as the first argument
// and no second argument
var someObject = {};
managerA.send('anAction', someObject);
// the 'anAction' method of 'stateOne.substateOne' is called again
// with managerA as the first argument and
// someObject as the second argument.
```
If the StateManager attempts to send an action but does not find an appropriately named
method in the current state or while moving upwards through the state hierarchy, it will
repeat the process looking for a `unhandledEvent` method. If an `unhandledEvent` method is
found, it will be called with the original event name as the second argument. If an
`unhandledEvent` method is not found, the StateManager will throw a new Ember.Error.
```javascript
var managerB = Ember.StateManager.create({
initialState: 'stateOne.substateOne.subsubstateOne',
stateOne: Ember.State.create({
substateOne: Ember.State.create({
subsubstateOne: Ember.State.create({}),
unhandledEvent: function(manager, eventName, context) {
console.log("got an unhandledEvent with name " + eventName);
}
})
})
});
managerB.get('currentState.name'); // 'subsubstateOne'
managerB.send('anAction');
// neither `stateOne.substateOne.subsubstateOne` nor any of it's
// parent states have a handler for `anAction`. `subsubstateOne`
// also does not have a `unhandledEvent` method, but its parent
// state, `substateOne`, does, and it gets fired. It will log
// "got an unhandledEvent with name anAction"
```
Action detection only moves upwards through the state hierarchy from the current state.
It does not search in other portions of the hierarchy.
```javascript
var managerC = Ember.StateManager.create({
initialState: 'stateOne.substateOne.subsubstateOne',
stateOne: Ember.State.create({
substateOne: Ember.State.create({
subsubstateOne: Ember.State.create({})
})
}),
stateTwo: Ember.State.create({
anAction: function(manager, context) {
// will not be called below because it is
// not a parent of the current state
}
})