【问题标题】:Custom Element - null reference from query() in constructor自定义元素 - 来自构造函数中 query() 的空引用
【发布时间】:2013-04-05 05:09:25
【问题描述】:

我正在开发我的第一个 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();
  }

}

【问题讨论】:

    标签: dart dart-webui


    【解决方案1】:

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

    也就是说,我能问一下您为什么需要使用这种特殊的方法来添加孩子吗?像这样使用template repeat 可能更容易做到这一点:

    <!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>
    

    那么你的任何菜单显示代码都不需要放在你的构造函数中。

    【讨论】:

    • 谢谢,马特。我选择我的方法只是因为这是这个 Dart 菜鸟能想到的第一件事。我认为您的解决方案正是我正在寻找的。从这里开始,我将努力动态填充 menuItems。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2023-03-18
    • 2020-04-17
    • 2017-03-22
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多