createCommand.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import defaultValue from '../Core/defaultValue.js';
  2. import defined from '../Core/defined.js';
  3. import defineProperties from '../Core/defineProperties.js';
  4. import DeveloperError from '../Core/DeveloperError.js';
  5. import Event from '../Core/Event.js';
  6. import knockout from '../ThirdParty/knockout.js';
  7. /**
  8. * Create a Command from a given function, for use with ViewModels.
  9. *
  10. * A Command is a function with an extra <code>canExecute</code> observable property to determine
  11. * whether the command can be executed. When executed, a Command function will check the
  12. * value of <code>canExecute</code> and throw if false. It also provides events for when
  13. * a command has been or is about to be executed.
  14. *
  15. * @exports createCommand
  16. *
  17. * @param {Function} func The function to execute.
  18. * @param {Boolean} [canExecute=true] A boolean indicating whether the function can currently be executed.
  19. */
  20. function createCommand(func, canExecute) {
  21. //>>includeStart('debug', pragmas.debug);
  22. if (!defined(func)) {
  23. throw new DeveloperError('func is required.');
  24. }
  25. //>>includeEnd('debug');
  26. canExecute = defaultValue(canExecute, true);
  27. var beforeExecute = new Event();
  28. var afterExecute = new Event();
  29. function command() {
  30. //>>includeStart('debug', pragmas.debug);
  31. if (!command.canExecute) {
  32. throw new DeveloperError('Cannot execute command, canExecute is false.');
  33. }
  34. //>>includeEnd('debug');
  35. var commandInfo = {
  36. args : arguments,
  37. cancel : false
  38. };
  39. var result;
  40. beforeExecute.raiseEvent(commandInfo);
  41. if (!commandInfo.cancel) {
  42. result = func.apply(null, arguments);
  43. afterExecute.raiseEvent(result);
  44. }
  45. return result;
  46. }
  47. command.canExecute = canExecute;
  48. knockout.track(command, ['canExecute']);
  49. defineProperties(command, {
  50. beforeExecute : {
  51. value : beforeExecute
  52. },
  53. afterExecute : {
  54. value : afterExecute
  55. }
  56. });
  57. return command;
  58. }
  59. export default createCommand;