2

我正在尝试更改使用聚合物库的默认 Web 应用程序,以便从 DART 代码创建聚合物元素并将其添加到 DOM,而不是包含在 HTML 中。我已成功将元素添加到 DOM,但我的可观察变量没有在 DOM 上更新。事件被触发,值正在改变。我已经使用 Observable.dirtyCheck() 更新了 DOM,但是,这显然很昂贵,所以我试图弄清楚如何让聚合物在没有dirtyCheck() 的情况下更新 dom。

所以,简而言之,我如何摆脱 Observable.dirtyCheck() ???

动态创建.dart

library dynamiccreate;

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



main() {
  initPolymer();

  //create click-counter element at runtime from DART, not HTML
  var NewElement = new Element.tag('click-counter');
  NewElement.setAttribute("count", "5");
  //Add to DOM
  querySelector('#sample_container_id').children.add(NewElement);
}

动态创建.html

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Sample app</title>
    <link rel="stylesheet" href="dynamiccreate.css">

    <!-- import the click-counter -->
    <link rel="import" href="clickcounter.html">
    <!-- <script type="application/dart">export 'package:polymer/init.dart';</script> -->
    <script src="packages/browser/dart.js"></script>
  </head>
  <body>
    <h1>DynamicCreate</h1>

    <p>Hello world from Dart!</p>

    <div id="sample_container_id">
     <!--  <click-counter count="5"></click-counter> -->
    </div>
    <script src="dynamiccreate.dart" type="application/dart"></script>
  </body>
</html>

点击计数器.dart

import 'package:polymer/polymer.dart';

/**
 * A Polymer click counter element.
 */
@CustomTag('click-counter')
class ClickCounter extends PolymerElement {
  @published int count = 0;

  ClickCounter.created() : super.created() {
  }

  //increment gets called when dynamically adding object at runtime
  //But does not update count on DOM
  void increment() {
    count++;
    //Have to add this to update count in DOM
    Observable.dirtyCheck(); //<<<---How do I get rid of this???
  }
}

点击计数器.html

<polymer-element name="click-counter" attributes="count">
  <template>
    <style>
      div {
        font-size: 24pt;
        text-align: center;
        margin-top: 140px;
      }
      button {
        font-size: 24pt;
        margin-bottom: 20px;
      }
    </style>
    <div>
      <button on-click="{{increment}}">Click me</button><br>
      <span>(click count: {{count}})</span>
    </div>
  </template>
  <script type="application/dart" src="clickcounter.dart"></script>
</polymer-element>
4

1 回答 1

5

将您的 dynamiccreate.dart 文件更改为如下所示,计数器开始在 UI 中递增:

library dynamiccreate;

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

main() {
  initPolymer().run(() {
    var newElement = new Element.tag('click-counter');
    newElement.setAttribute("count", "15");
    querySelector('#sample_container_id').children.add(newElement);
  });
}

尼特:命名你的变量newElement,而不是NewElement. 固定在这里。

于 2013-11-19T08:58:17.057 回答