Using internal function in controler

Hi,

i want to call a function in the same controller from connect() but i dont know how it should work.
Any suggestion?

Thanks a lot
Mok

can give provide a code sample of what you are trying to accomplish?


export default class extends Controller {

  connect(event) {
        jQuery('#viewByRegister').click(function(event) {
            jQuery('.viewByRegister').show();
            jQuery('#newLandregisterDiv').show();
            jQuery(this).addClass("act");
            jQuery('#viewBySections').removeClass("act");
            jQuery('.viewByInventoryListing').hide();
            jQuery('.viewBySectionOne').hide();
            jQuery('#sectionsSubNavi').hide();
            jQuery('.viewBySectionTwo').hide();
        });
}

CHANGE TO:

 connect(event) {
        jQuery('#viewByRegister').click(function(event) {
            jQuery(this).addClass("act");
            hideShowFields('register');
        });
   }

   hideShowFields(param) {
        DO_THE_JOB
   } 

To call other functions inside of a javascript class, you need to use this.

connect(event) {
  jQuery('#viewByRegister').click(function(event) {
    jQuery(this).addClass("act");
-   hideShowFields('register');
+   this.hideShowFields('register');
  });
}

However, this will not work because this has a different scope inside the function.

connect(event) {
+ this //-> controller class
  jQuery('#viewByRegister').click(function(event) {
    jQuery(this).addClass("act");
+   this //-> jQuery object;
  });
}

There are multiple ways to solve this:

  • Use the bind() function
  • Store a reference to context/this inside another variable
  • Arrow function

Here’s an example of bind function (untested), which also gives the flexibility of calling it separately from HTML (e.g. data-action="click->my-controller#click"):

connect(event) {
  jQuery('#viewByRegister').click(this.click.bind(this))
}

click(event) {
  Query(event.target).addClass("act");
  this.hideShowFields('register');
}

hideShowFields(param) {
   DO_THE_JOB
} 
1 Like

Hi, sorry for late reply.

It is nearly working. Thank you a lot.

Regards