2

So I have something like

this.editElement = $("<a href='#'>Edit</a>").click(function() {
    this.startEdit();
});

This however takes "this" to be the editElement itself, rather than the parent object.

I've managed to get it to work by making a

var parent = this;

before setting click and then using parent enough of this.

Is this the correct way to solve the problem?

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
Fricken Hamster
  • 541
  • 3
  • 7
  • 15

1 Answers1

0

That's a very correct way, yes, and it's common.

You also took the right decision in naming it parent instead of the semantic-less _this we often see.

Other solutions :

  • to bind the callback to the external this
  • to use the data argument of JQuery's on to pass the parent
  • to dynamically find the parent from the callback

but most often referring to a variable kept in the external closure as you did is the cleanest solution.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697