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") : 

Here is what I've done:

import $ from 'jquery';

export default class FormListener {
  constructor(selector=".select-element") {
  change() {
    let $item = $(this);
    let value = $item.val();
    let $nextElements = $item.nextAll();
    let $nextElement = $item.next();
    value === 0 ?
      $nextElements.addClass("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?

  • \$\begingroup\$ I'm not sure if this is valid JS nor if this even works at all. \$\endgroup\$ – Joseph May 14 '16 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.