Advertisement
Guest User

Untitled

a guest
May 27th, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. 'use strict';
  2.  
  3. var _ = require('lodash');
  4.  
  5. /**
  6. * @class StateMachine
  7. * @constructor
  8. */
  9. function StateMachine(options) {
  10. /**
  11. * @type {Object}
  12. */
  13. this.options = options;
  14.  
  15. /**
  16. * current state
  17. * @type {String}
  18. */
  19. this.currentState = options.state;
  20.  
  21. /**
  22. * state transitions
  23. * @type {Object}
  24. */
  25. this.transitions = {};
  26. }
  27.  
  28. /**
  29. * Returns the current state of the state machine
  30. * @method getState
  31. */
  32. StateMachine.prototype.getState = function getState() {
  33. return this.currentState;
  34. };
  35.  
  36. /**
  37. * merge into the internal transitions
  38. * @method addTransitions
  39. * @param {Object} transitions
  40. */
  41. StateMachine.prototype.addTransitions = function addTransitions(transitions) {
  42. return _.extend(this.transitions, transitions);
  43. };
  44.  
  45. /**
  46. * Update the current state and call the state transition method
  47. * @method changeState
  48. * @param {String} state
  49. */
  50. StateMachine.prototype.changeState = function changeState() {
  51. // take the given state out of the arguments array
  52. var state = [].shift.apply(arguments);
  53. var context = this.options.context || null;
  54.  
  55. if(!!this.transitions) {
  56. var transition = this.transitions[this.currentState + ' > ' + state];
  57. var fromTransition = this.transitions[this.currentState + ' >'];
  58. var toTransition = this.transitions['> ' + state];
  59.  
  60. if (!!fromTransition) {
  61. fromTransition.apply(context, arguments);
  62. }
  63.  
  64. if (!!transition) {
  65. transition.apply(context, arguments);
  66. }
  67.  
  68. if (!!toTransition) {
  69. toTransition.apply(context, arguments);
  70. }
  71. }
  72. this.currentState = state;
  73. };
  74.  
  75. module.exports = StateMachine;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement