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?
- class SearchVenues {
- constructor() {
- this.categoriesSelector = $('#catgories');
- this.distanceSelector = $('#venue-distance');
- this.state = {
- category_ids: [],
- distance: null
- };
- this.url = "/some/path";
- this.resultContainer = $("#results");
- }
- onCategoriesChange(event) {
- const {
- category_ids
- } = this.state.category_ids;
- const {
- value
- } = event.target;
- if (category_ids.includes(value)) {
- this.state.category_ids = category_ids.filter(function(id) {
- return id !== value;
- });
- } else {
- this.state.category_ids = category_ids.concat(val);
- }
- this.fetch();
- }
- onDistanceChange(event) {
- const {
- value
- } = event.target;
- this.state.distance = value;
- this.fetch();
- }
- fetch() {
- $.get(this.url,
- this.state,
- function(data) {
- this.resultContainer.html(data);
- });
- }
- init() {
- this.categoriesSelector.on('change', this.onCategoriesChange);
- this.distanceSelector.on('change', this.onDistanceChange);
- }
- }