Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following javascript code that I'm trying to modularize using ES6:

import $ from 'jquery';

$('.select-element').change(function() {
  const $this = $(this);
  const $nextElements = $this.nextall();
  const $nextElement = $this.next();
  $this.val() === 0 ? 
    $nextElements.addClass("hidden") : 
    $nextElement.removeClass("hidden");
});

Here is what I've done:

import $ from 'jquery';

export default class FormListener {
  constructor(selector=".select-element") {
    $(selector).change(this.change);
  }
  change() {
    let $item = $(this);
    let value = $item.val();
    let $nextElements = $item.nextAll();
    let $nextElement = $item.next();
    value === 0 ?
      $nextElements.addClass("hidden") :
      $nextElement.removeClass("hidden");
  } 
}  

Then in my code, rather than simply insert the first version inside a <script> tag, I do this:

import FormListener from './form-listener');
new FormListener();

I got the basic ideas from the jQuery code organization docs but tried to use a class rather than a function. Is this the proper way to modularize a simple jQuery listener? Is there a better coding pattern to follow to achieve my goal?

share|improve this question
    
I'm not sure if this is valid JS nor if this even works at all. – Joseph the Dreamer May 14 at 5:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.