在动态添加dart聚合物元素时,如何在DOM上获取可观察变量

前端之家收集整理的这篇文章主要介绍了在动态添加dart聚合物元素时,如何在DOM上获取可观察变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试更改使用聚合物库的默认Web应用程序,以便创建聚合物元素并将其从DART代码添加到DOM,而不是包含在HTML中.我已成功将元素添加到DOM中,但我的可观察变量未在DOM上更新.事件正在被解雇,价值正在发生变化.我已经使用Observable.dirtyCheck()更新了DOM,但是,这显然很昂贵,所以我试图弄清楚如何在没有dirtyCheck()的情况下让聚合物更新dom.

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

dynamiccreate.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);
}

dynamiccreate.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>

clickcounter.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???
  }
}

clickcounter.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>

解决方法

将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);
  });
}

Nit:将变量命名为newElement,而不是NewElement.固定在这里.

原文链接:https://www.f2er.com/html/232167.html

猜你在找的HTML相关文章