3

我正在开发我的第一个 Dart 应用程序,已经完成了 Game of Darts 教程。我正在尝试创建一个语义命名的顶级菜单元素,该元素最终将在我的页面顶部显示导航菜单选项卡列表。我的 Dart 应用程序能够识别我的自定义元素并调用关联的构造函数。

但是,当我尝试在我的自定义元素中查询 UL 元素时,我得到了一个空引用。我需要 UL 参考才能将我的 LI 元素动态加载到菜单中。

问题 1:该元素是否应该在 DOM 中在构造函数运行时可见?

问题 2:如果还不可见,在自定义元素完全加载到 DOM 后,是否可以使用 Dart 事件来触发加载 LI 元素?

提前致谢!作为参考,这是我的自定义元素的来源:

topmenu-element.html

<!DOCTYPE html>

<html>
  <body>
    <element name="top-menu" constructor="TopMenu" extends="div">
      <template>
        <div>
          Top Menu
          <ul id="top-menu-list"></ul>
        </div>
      </template>
      <script type="application/dart" src="topmenu-element.dart"></script>
    </element>
  </body>
</html>

topmenu-element.dart

import 'package:web_ui/web_ui.dart';
import 'dart:html';

class TopMenu extends WebComponent {

  List menuItems = ['Session', 'Authentication Services', 'Vehicle Services', 'Subscriber Services', 'Data Services'];

  void populateMenu() {
    UListElement menuList = query('#top-menu-list');
    LIElement newMenuItem = new LIElement();
    newMenuItem.text = menuItems[0];
    menuList.children.add(newMenuItem);
  }

  TopMenu() {
    // populateMenu();
  }

}
4

1 回答 1

2

我不能具体谈论带有查询方法的构造函数中的 DOM 可见性,因为我真的不确定。但是,您可能可以使用更好的方法,这些方法在元素生命周期的各个阶段被调用。

也就是说,我能问一下为什么你需要使用这种特殊的方法来添加孩子吗?使用模板重复可能更容易做到这一点,如下所示:

<!DOCTYPE html>

<html>
  <body>
    <element name="top-menu" constructor="TopMenu" extends="div">
      <template>
        <div>
          Top Menu
          <ul id="top-menu-list">
            <li template repeat="item in menuItems">{{item}}</li>
          </ul>
        </div>
      </template>
      <script type="application/dart" src="topmenu-element.dart"></script>
    </element>
  </body>
</html>

那么就不需要将任何菜单显示代码放入构造函数中。

于 2013-04-12T15:41:13.407 回答