0

I have an object constructor function that I use to create an object for a Conway's Game of Life simulator. A table element is used to render the game and the cells.

A user can click on a cell to toggle it being alive/dead. For this reason, every cell has an event listener,

cell.addEventListener( 'click', myObjConstructor.toggleState ) 

The way handlers work is that when the listener calls the handler function, "this" refers to the element the listener is placed in (rather than the object's this) which is why this wouldn't work:

cell.addEventListener( 'click', this.toggleState )

Because this would reference the element (the cell) which wouldn't have a "toggleState" method thus results in an error.

I think this is pretty standard knowledge regarding handlers. My question is, what is the most "professional" way of dealing with this when you want to reference the object's this?

The way I am dealing with it is I declare this dummy variable at the beginning of my object:

myBackupThis = this;

However, this feels "cheap". I am assuming the pros must handle it in a different way.

I tried an arrow function but it doesn't solve the problem that "this" is not pointing to the object.

joe
  • 1
  • 1
    `this.toggleState.bind(this)` – Keith Oct 31 '22 at 15:58
  • An arrow function should work just fine. What exactly did you try? – Bergi Oct 31 '22 at 15:59
  • 1
    What is the context of that line of code in your question ? Where is the `cell.addEventListener` being called from ? – Gabriele Petrioli Oct 31 '22 at 16:04
  • 1
    `I tried an arrow function`, If you tried -> `cell.addEventListener( 'click', () => this.toggleState() )` then `this` would be the same `this` that you invoked it with. Please note if you use an arrow function, don't forget you also need to invoke the function, IOW: `() => func()`, and not `() => func`.. – Keith Oct 31 '22 at 16:07
  • _“every cell has an event listener”_ — Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296/4642212). – Sebastian Simon Oct 31 '22 at 16:10

0 Answers0