0

I'm pretty bad with OOP principles, so this is gonna be hard for me to explain, but here goes.

What I'm trying to do is move a "window.resize" event handler into a class, and have any objects instantiated from said class deal with its own resizing, but the problem is that when I move the handler into the class, and the handler then fires, the object can't seem to access it's own properties - their all undefined.

Let me rather show you what I'm trying to do.

My current (working) code:

// index.js
window.addEventListener('resize', resize);

let thing;
function setup() {
    thing = new CustomThing();
}

function resize() {
    thing.resize();
}

setup();


// CustomThing.js
class CustomThing {
    constructor() {
        this.background = { width:100, height:100 };
    }

    resize() {
        console.log('I\'m successfully resizing. Yay!');
        this.background.width = window.innerWidth;
    }
}

I'm trying to turn the above code into the following:

// index.js
let thing;
function setup() {
    thing = new CustomThing();
}
setup();
// Notice that I don't have the event listener or resize function here anymore


// CustomThing.js
class CustomThing {
    constructor() {
        this.background = { width:100, height:100 };
        window.addEventListener('resize', this.resize);
    }

    resize() {
        console.log('this.background is now undefined :(');
        this.background.width = window.innerWidth;
    }
}

I've also tried changing the above window.addEventListener('resize', this.resize); to window.addEventListener('resize', () => this.resize(this.background));, and resize() into resize(background), and then only using background in the resize function instead of this.background, in which case I can actually access the background's properties. But then it's as if it creates a copy of this.background for me to manipulate, becuase my object doesn't actually resize.

So my question is: How can I refactor the below code, so that I can have the resize event handler in my class, call a function when it triggers, and then successfully access the class' other properties from within the function that got called?

FWIW, this is taken (and simplified) from a PIXI.js application I'm working on. Let me know if I need to include more details or bring in some of the code from my actual PIXI application.

SeriousLee
  • 1,301
  • 4
  • 20
  • 42

0 Answers0