createCommand.js 1.8 KB

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