PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Source/Bifrost.Web/Scripts/bifrost.commands.js

#
JavaScript | 94 lines | 79 code | 15 blank | 0 comment | 15 complexity | f52de5730d9585c0927016cfedc7c729 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. var Bifrost = Bifrost || {};
  2. if (typeof ko === 'undefined') {
  3. throw "Requires Knockout.js";
  4. }
  5. ko.bindingHandlers.command = {
  6. init: function (element, valueAccessor, allBindingAccessor, viewModel) {
  7. ko.applyBindingsToNode(element, { click: valueAccessor().execute }, viewModel);
  8. }
  9. };
  10. (function () {
  11. function S4() {
  12. return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  13. }
  14. function guid() {
  15. return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  16. }
  17. function CommandDescriptor(name, commandParameters) {
  18. this.Name = name;
  19. var commandContent = {
  20. Id: guid()
  21. };
  22. for (var parameter in commandParameters) {
  23. if (typeof (commandParameters[parameter]) == "function") {
  24. commandContent[parameter] = commandParameters[parameter]();
  25. } else {
  26. commandContent[parameter] = commandParameters[parameter];
  27. }
  28. }
  29. this.Command = JSON.stringify(commandContent);
  30. };
  31. function Command() {
  32. var self = this;
  33. this.hasError = false;
  34. this.isBusy = ko.observable();
  35. this.canExecute = ko.observable(true);
  36. this.execute = function () {
  37. self.hasError = false;
  38. if (self.beforeExecute) {
  39. self.beforeExecute(self);
  40. }
  41. if (!self.canExecute()) {
  42. return;
  43. }
  44. self.isBusy(true);
  45. $.ajax({
  46. url: "CommandCoordinator/handle",
  47. type: 'POST',
  48. dataType: 'json',
  49. data: JSON.stringify(new CommandDescriptor(self.name, self.parameters)),
  50. contentType: 'application/json; charset=utf-8',
  51. error: function (e) {
  52. self.hasError = true;
  53. self.error = e;
  54. if (self.onError != undefined) {
  55. self.onError(self);
  56. }
  57. },
  58. complete: function () {
  59. if (!self.hasError) {
  60. if (self.onSuccess != undefined) {
  61. self.onSuccess(self);
  62. }
  63. }
  64. if (self.onComplete != undefined) {
  65. self.onComplete(self);
  66. }
  67. self.isBusy(false);
  68. }
  69. });
  70. };
  71. };
  72. Bifrost.commands = {
  73. create: function (configuration) {
  74. var cmd = new Command();
  75. $.extend(cmd, configuration);
  76. return cmd;
  77. }
  78. };
  79. })();