Help/Review how to write modular Jquery code

Help/Review how to write modular Jquery code

I tried to write a modular Jquery code as this https://learn.jquery.com/code-organization/concepts/ said. Can anyone review my code and give me advises to improve it?

Is there a better way to do the fetch operations than I am doing?

Can I expose only the `init` methods as a public API?


  1. class SearchVenues {
  2.     constructor() {
  3.       this.categoriesSelector = $('#catgories');
  4.       this.distanceSelector = $('#venue-distance');
  5.       this.state = {
  6.         category_ids: [],
  7.         distance: null
  8.       };
  9.       this.url = "/some/path";
  10.       this.resultContainer = $("#results");
  11.     }

  12.     onCategoriesChange(event) {
  13.       const {
  14.         category_ids
  15.       } = this.state.category_ids;

  16.       const {
  17.         value
  18.       } = event.target;

  19.       if (category_ids.includes(value)) {
  20.         this.state.category_ids = category_ids.filter(function(id) {
  21.           return id !== value;
  22.         });
  23.       } else {
  24.         this.state.category_ids = category_ids.concat(val);
  25.       }

  26.       this.fetch();
  27.     }

  28.     onDistanceChange(event) {
  29.       const {
  30.         value
  31.       } = event.target;

  32.       this.state.distance = value;
  33.       this.fetch();
  34.     }

  35.     fetch() {
  36.       $.get(this.url,
  37.         this.state,
  38.         function(data) {
  39.           this.resultContainer.html(data);
  40.         });
  41.     }

  42.     init() {
  43.       this.categoriesSelector.on('change', this.onCategoriesChange);
  44.       this.distanceSelector.on('change', this.onDistanceChange);
  45.     }
  46.   }