Licitator 1.0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.0 KiB

5 years ago
  1. "use strict";
  2. var ruleBuilders = {};
  3. (function ($) {
  4. $.fn.ruleBuilder = function (options) {
  5. var id = $(this).data("rule-builder-id");
  6. if (options === "data") {
  7. return (typeof ruleBuilders[id] === "undefined") ? {} : ruleBuilders[id].collectData();
  8. } else {
  9. return $(this).each(function () {
  10. // Validate options
  11. if (typeof options.fields === 'undefined' || options.fields.length === 0) {
  12. throw new Error('Missing definitions');
  13. }
  14. var ruleData = (typeof options.data !== "undefined" && options.data !== '') ?
  15. JSON.parse(options.data) : {};
  16. if (id) {
  17. ruleBuilders[id].remove();
  18. delete ruleBuilders[id];
  19. }
  20. var builder = new RuleBuilder(this, options.fields, ruleData);
  21. ruleBuilders[builder.getId()] = builder;
  22. $(this).data("rule-builder-id", builder.getId());
  23. });
  24. }
  25. };
  26. /**
  27. * @param element
  28. * @param {Object} fields
  29. * @param {Object} ruleData
  30. * @constructor
  31. */
  32. function RuleBuilder(element, fields, ruleData) {
  33. this.id = guid();
  34. this.element = $(element);
  35. this.mainGroup = new Group(new Definitions(fields), ruleData, false);
  36. this.mainGroup.setChangeCallback(function () {
  37. this.element.trigger('rule-change');
  38. }.bind(this));
  39. this.appendHTML();
  40. }
  41. RuleBuilder.prototype = {
  42. /**
  43. * Returns the builder's id
  44. * @returns {*}
  45. */
  46. getId: function () {
  47. return this.id;
  48. },
  49. appendHTML: function () {
  50. this.element.html(this.mainGroup.appendHtml(this.element));
  51. },
  52. /**
  53. * Serialize the current condition
  54. */
  55. collectData: function () {
  56. return this.mainGroup.serialize();
  57. },
  58. remove: function () {
  59. this.mainGroup.remove();
  60. }
  61. }
  62. })(jQuery);