createCommand.js 2.3 KB

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