region-selection.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /// <reference path="../../node_modules/@types/jquery/index.d.ts"/>
  2. namespace RegionSelection {
  3. function foreach(data, callback: (value: any, key?: number | string, array?: Array<any>) => void) {
  4. Array.prototype.forEach.call(data, callback);
  5. }
  6. class RegionSelectionBox {
  7. private selector: JQuery;
  8. private regions: Region[] = [];
  9. private box: JQuery;
  10. constructor(selector: JQuery) {
  11. this.selector = selector;
  12. if (this.selector.data('regions') !== undefined) {
  13. this.fillRegions(this.selector.data('regions'));
  14. }
  15. this.selector.on('click', this.showBox.bind(this));
  16. }
  17. private fillRegions(data) {
  18. foreach(eval(data), (value: RegionInterface) => {
  19. this.regions.push(new Region(value));
  20. });
  21. }
  22. private showBox(e: JQueryEventObject) {
  23. e.preventDefault();
  24. if (this.box === undefined) {
  25. this.renderBox();
  26. }
  27. this.box.toggle();
  28. }
  29. private renderBox() {
  30. let box = $('<div class="region__selection-box"></div>');
  31. let itemTemplate = '<a href="{link}" class="region__selection-item">{name}</a>';
  32. foreach(this.regions, (region: Region) => {
  33. let item = $(itemTemplate
  34. .replace('{link}', region.link)
  35. .replace('{name}', region.caption)
  36. );
  37. box.append(item);
  38. });
  39. box.css('display', 'none');
  40. this.selector.parent().append(box);
  41. this.box = box;
  42. }
  43. }
  44. interface RegionInterface {
  45. id: number;
  46. caption: string;
  47. link: string;
  48. icon: string;
  49. }
  50. class Region {
  51. constructor(data: RegionInterface) {
  52. this._id = data.id;
  53. this._caption = data.caption;
  54. this._link = data.link;
  55. this._icon = data.icon;
  56. }
  57. private _id: number;
  58. get id() {
  59. return this._id;
  60. }
  61. private _caption: string;
  62. get caption() {
  63. return this._caption;
  64. }
  65. private _link: string;
  66. get link(): string {
  67. return this._link;
  68. }
  69. private _icon: string;
  70. get icon(): string {
  71. return this._icon;
  72. }
  73. }
  74. export function createSelectionBox($object: JQuery) {
  75. return new RegionSelectionBox($object);
  76. }
  77. }