1

I'd like to reference "this" (a method owner) while method cascading in Dart.

// NG code, but what I want.
paragraph.append( getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (this.text + " has been has clicked"); // <= Error. Fail to reference "button.text".
    }));

I know I can write a code like this by splitting it onto multiple lines.

// OK code, I think this is verbose.
var button;
button = getButton()
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been clicked");
    }));
paragraph.append( button);

Being unable to reference a cascading source object is preventing me from writing shorter code on many occasions. Is there better way to do method cascading?

Pixel Elephant
  • 20,649
  • 9
  • 66
  • 83

1 Answers1

2

You can not use this as you would like.

You can simplify your second code snippet with :

var button = getButton();
paragraph.append(button
    ..text = "Button A"
    ..onClick.listen((e) {
      print (button.text + " has been has clicked");
    }));
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • To expand on that, Dart is lexically scoped, so "this" would never refer to the button that you're creating. It refers to the object in which the entire method is running. And that probably doesn't have a text method. You could see that fairly easily by changing to "this.toString()" – Alan Knight Mar 07 '14 at 18:28