sniffingdoggo
sniffingdoggo

Reputation: 406

How to use a variable of second constructor function in Node.js? (using import/export)

I have 3 different .js files that are linked between them by import/export keywords. Each of the files have their own specific functions like this:


  1. Init.js: Invokes Event.js and Touch.js. Send the variables to Event.js.

  2. Event.js: Receives the variables from Init.js and registers the event to each of the elements.

  3. Touch.js: Recognizes the event id from Event.js then logs it.


A problem is the constructor function of Touch.js doesn't work at all. The browser can't access to it. It keeps firing undefined when I try to log it the local variables called A and B.

The only possible way that I've found is to create the variables from Init.js, pass them to Event.js, and pass again to Touch.js like I've done below.

Are there any ways to use the local variables of its own constructor function?

See the code below:

//============== Init.js ==============
'use strict';
import {Event} from './event.js';
import { proTouch } from './touch.js';
const slider = (function() {
    class Slider {
        constructor(elem) {
            this.elem = document.querySelectorAll(elem);
            this.C = false;
            this.Event = new Event();
            this.Event.register(this.elem, 'mouseenter', proTouch.start, this.C);
        }
    }
    return {
        initialize: new Slider('.box')
    }
}());

//============== Event.js ==============

export class Event {
    constructor() {

    }
    register(node, eventName, callback, flag) {
        let bind = callback.bind(this);
        node.forEach(cur => {
            cur.addEventListener(eventName, (e) => bind(e, flag))
        })
    }
}


//============== Touch.js ==============

class Touch {
    constructor() {
        this.A = false;
        this.B = true; // <-- I want to use this constructor function.
    }
    start(e, flag) {
        console.log(e.type, this.A, this.B, flag); // <-- this.A and this.B fire undefined.
    }
}
const proTouch = new Touch();
export { proTouch }

Upvotes: 0

Views: 129

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12552

In your Event class, you are binding the callback to this. That is wrong because in this context this is Event instance and doesn't contain a or b variable. Delete that line.

let bind = callback.bind(this);//Wrong. Delete this line.

When you are Sending the callback you want to bind the proTouch to the start method. So, bind there.

this.Event.register(this.elem, 'mouseenter', proTouch.start.bind(proTouch), this.C);

Upvotes: 1

Related Questions