0

I am trying to build a JS application that instantiates new contact object when the form is filled. However, when it comes to classes I am struggling to create logic between getting the input fields and instantiating the contact.

Code so far.

Class to create contact on click.

export class Create {

    addEventListeners () {
        document.querySelector('#new-contact').addEventListener("click", createContact);
    }

    createContact () {
        let contact = new Contact({
            contFn: 'Tim',
            contLn: 'Cook'
        })
    }

}

Class for the contact.

'use strict';

export class Contact {

    constructor (contFn, contLn, contEmail, contPhone, contSocial) {
        this.contFn = contFn;
        this.contLn = contLn;
        this.contEmail = contEmail;     
        this.contPhone = contPhone;
        this.contSocial = contSocial;
    }

    printContact () {
        console.log(this.contFn);
        console.log(this.contLn);
    }

}

window.addEventListener('load', () => new Contact());
cnic
  • 480
  • 1
  • 5
  • 13

1 Answers1

1

createContact is undefined. There is no variable with that name. It's a method, a property inherited from the prototype of the instances. You have to access it as this.createContact. But assuming you are using the Create instance inside the method, you can't just pass it around without losing context, so you should do

addEventListeners () {
    document.querySelector('#new-contact').addEventListener("click", (e) => this.createContact(e));
}

Notice that you probably shouldn't use a class here if it doesn't do anything else.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Would `this.discasrd = this.createContact.bind(this);` in the constructor have the same desired affect as `addEventListener("click", (e) => this.createContact(e));`? – cnic Apr 17 '16 at 11:40
  • Yes, you can do that as well, it would be `….addEventListener("click", this.discasrd)` then – Bergi Apr 17 '16 at 13:11