createCommand.js 1.9 KB

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