2

如何获得paper-input下面元素的实例?

HTML 文件:

<!DOCTYPE html>
<html>
<head>
  <!-- <script src='packages/web_components/platform.js'></script>
       not necessary anymore with Polymer >= 0.14.0 -->
  <script src='packages/web_components/dart_support.js'></script>    
  <link rel='import' href='packages/paper_elements/paper_input.html'>
  <script src='packages/browser/dart.js'></script>
</head>
<body fullbleed unresolved>
  <paper-input id='subject' label='subject'></paper-input>
  <script type='application/dart' src='myscript.dart'></script>
</body>
</html>

myscript.dart:

import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:paper_elements/paper_input.dart';
export 'package:polymer/init.dart';
PaperInput _subject = querySelector('#subject');    // exception
void main() {
  ...
}

这会导致异常:

Breaking on exception: type 'HtmlElement' is not a subtype of type 'PaperInput'

从 HtmlElement 转换为 PaperInput 不起作用。建议包括 usingshadowRoot.querySelector('#subject');和其他shadowRoot用法,但它来自哪里?如果我追加.shadowRoot.querySelector('paper-input')到 myscript.dart 的最后一行,则该元素为空。如果我使用 id 而不是标签名称,结果相同。元素本身是 html 正文的顶级元素,因此它不在任何其他 shadowRoot 中。

paper-input如果不属于 PaperInput 类,就无法获取 的内容。但似乎没有办法施放它。

4

1 回答 1

4

您遇到了如何在聚合物应用程序中实现主要功能

当您像下面所示或在 Polymer 元素内执行此操作时(在某些单击或其他事件处理程序attached()之后或中(当元素正确初始化时)super.attached()

main() {
  initPolymer().run(() {
    // code here works most of the time
    Polymer.onReady.then((_) {     
      // some things must wait until onReady callback is called
      // for an example look at the discussion linked below

      PaperInput _subject = querySelector('#subject');
    });
  });
}
于 2014-07-14T21:41:25.973 回答