1

I have the following javascript class similar to this:

class ModalFormButton {

  constructor() {
    this.contactForm = new ContactForm();
    let utils = new Utils();
    this.$signupModal = $(utils.getModalTmpl());
  }

  loadContactForm() {
    this.$signupModal.modal();
    this.contactForm.load();
  }

  contactBtnHandler(e) {
    e.preventDefault();
    let utils = new Utils();
    var $t = $(this),
        $modalTitle = $t.data('modal-title'),
        $modalFormId = $t.data('modal-form-id');

    $('body').append(this.$signupModal);
    this.$signupModal.find('.modal-title').html($modalTitle);
    this.$signupModal.find('.modal-body').load($t.attr('href') + ' #' + $modalFormId,this.loadContactForm);
  };

  registerHandlers() {
    $('.modal-form-btn').click(this.contactBtnHandler);
  };

  load() {
    this.registerHandlers();
  };
}

My problem is that when contactBtnHandler is called I don't have access to class properties because the context belongs to modal-form-btn. I know I can solve this using an arrow function, but I am wondering about if its possible to separate in a function the logic in the callback (here is a short example but I have longer functions) in a way similar to the one I am using.

Thanks

Gerardo
  • 5,800
  • 11
  • 66
  • 94
  • What do you mean by "*separate in a function the logic in the callback*" - an arrow function would be separated logic, wouldn't it? – Bergi Sep 13 '17 at 16:30

2 Answers2

2

You can try binding "this" to your class in your callback handler

registerHandlers() {
    $('.modal-form-btn').click(this.contactBtnHandler.bind(this) );
  };
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42
1

One could do:

getHandler (){
  return e => {
    //this is ModalFormButton
  };
}

And then:

 $('.modal-form-btn').click(this.getHandler());
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151