4

Having a weird issue. In my Dart code I have some polymer components on the screen and one of them has a method I call from my main().

I grab a reference to it by doing

PolyComp poly = querySelector("#idOfPolymer");
poly.flash();

This works perfectly in dart. The page loads up and PolyComp starts to flash. However when I run this in Chrome by running Build Polymer app from the Dart IDE, I get an error that says cannot call flash() on null.

I ended up making it flash by just using an event bus and letting PolyComp listen to my event, but this is overkill.

What am I doing wrong? This happens in the latest Chrome, Firefox and Safari.

Edit:

I built the following polymer app to JS also and ran into the same issue. https://github.com/sethladd/dart-polymer-dart-examples/blob/master/web/todo_element/todo.html

Works on DartVM, not in Chrome because its calling a method on a null element.

Faisal Abid
  • 8,900
  • 14
  • 59
  • 91
  • Although this might seem strange: – Benjamin Gruenbaum Jan 05 '14 at 10:15
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Benjamin Gruenbaum Jan 05 '14 at 10:15
  • You should try debugging in chrome and inspecting around the generated code and see why you're getting null when using querySelector. Also did you make sure (inspected) that the element is there in when using chrome? – markovuksanovic Jan 05 '14 at 10:17
  • Hey Benjamin, I added some more detail. – Faisal Abid Jan 05 '14 at 10:17
  • it's not that the element does not exist Benjamin, it's rather that the element does exist but not yet (depending on the page construction) as a polymer element (PolyComp). Once it becomes a real polymer element the querySelector can find it correctly. – Paul Collingwood Jan 05 '14 at 13:06
  • possible duplicate of [how to implement a main function in polymer apps](http://stackoverflow.com/questions/20982489/how-to-implement-a-main-function-in-polymer-apps) – Günter Zöchbauer Mar 18 '14 at 14:30

1 Answers1

7

When you run this code from the main() method it is probably a timing issue. You can try something like

import "package:polymer/polymer.dart";

main() {
  initPolymer().run(() {
    // code here works most of the time
    Polymer.onReady.then((e) {     
      // some things must wait until onReady callback is called
    });
  });
}

see also how to implement a main function in polymer apps

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • It's always the same way ? It works, but if I try to run `pub build`, it not work (does not compile). – Druxtan Jul 25 '14 at 17:30
  • @Druxtan can you please create another question and add the error output. The form of the script tag is outdated - I'll update this post. – Günter Zöchbauer Jul 25 '14 at 18:10