1

I think I'm lacking in a fundamental understanding of dart, but basically what I want to do is something like this:

void main() {
  new MyClass();
}

class MyClass {

  MyClass() {
    CanvasElement canvas = querySelector("#myCanvas");
    CanvasRenderingContext2D context = canvas.context2D;
  }
}

However, canvas is a null object by the time I try to get the context. How can I do this from within the class. Also, I don't want to do this:

void main() {
  CanvasElement canvas = querySelector("#myCanvas");
  new MyClass(canvas);
}

class MyClass {
  CanvasElement canvas
  MyClass(this.canvas) {
    canvas = this.canvas;
    CanvasRenderingContext2D context = canvas.context2D;
  }
}

Because I need to be able to do this completely from within the class. Is this just not how dart works, or am I missing something?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Zane Hitchcox
  • 936
  • 1
  • 9
  • 23

1 Answers1

3

Did you try your second example? It doesn't make a difference if you call querySelector from main() or from within a class.

Do you use Angular or Polymer? Angular or Polymer components introduce shadowDOM. querySelector() doesn't cross shadowDOM boundaries and it therefore doesn't find elements inside an elements shadowDOM.

To query for elements inside a shadowDOM you query for the component and then you can continue the search.

querySelector("somecomponent").shadowRoot.querySelector("someothercomponent").shadowRoot.querySelector("#myCanvas");

You have to ensure that the DOM including all shadowDOMs is fully built before you can query them. If you run your code from within a component pub your code into the onShadowRoot method (see NgComponent ready event for more details)

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Wow, you're absolutely right, I stand corrected. And you are also right that I was using Angular before which is what led me to believe that, but it turned out I had just messed up something in my code. Do you know how I would achieve this effect in angular now that shadow dom is deprecated? – Zane Hitchcox Jul 21 '14 at 04:08
  • I'm not sure what you mean by `shadow dom is deprecated`. I guess you mean the `shadow_dom` package http://pub.dartlang.org/packages/shadow_dom. This is only the package containing the shadowDOM polyfill for browsers without native support. The polyfill was added to the `web_components` package. – Günter Zöchbauer Jul 21 '14 at 04:15
  • Ahh, I see...but why can't you just interact with the regular DOM? – Zane Hitchcox Jul 21 '14 at 07:04
  • The shadowDOM of an Angular component or a Polymer element (or custom element) is the elements internal implementation (like for example of the ` – Günter Zöchbauer Jul 21 '14 at 07:15
  • Thanks, you are my hero! – Zane Hitchcox Jul 21 '14 at 21:28