在Web UI中使Map或List可观察

Sha*_*uli 8 dart dart-webui

我可以使用Dart代码中的@observable声明使String或num类型可观察:

@observable
var x = '';
Run Code Online (Sandbox Code Playgroud)

{{ }}html中的语法:

<div>x = {{x}}</div>
Run Code Online (Sandbox Code Playgroud)

@observable不适用于列表和地图.我如何制作那些可观察的?

Sha*_*uli 16

使用toObservable()与列表或地图作为参数.这将在List或Map对象及其在UI中的表示形式之间创建绑定.

以下示例使用toObservable().请注意,List和Map对象每秒都会添加数据.通过toObservable()创建正确的绑定,这些对象的UI会自动更新以显示添加的项目.

clear()编辑列表或地图时,UI再次反映了这一点.

有关如何构建和运行此脚本的说明,请参阅 http://www.dartlang.org/articles/web-ui/tools.html.

这是main.dart文件:

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

@observable
num x = 0;  // @observable works fine with a number. 

List list = toObservable(new List());

Map<String, num> map = toObservable(new Map());

void main() {
   new Timer.periodic(new Duration(seconds: 1), (_) {
     x += 1;
     list.add(x);
     map[x.toString()] = x;
     if (x % 4 == 0) {
       list.clear();
       map.clear();
     }
     return x;
   });
}
Run Code Online (Sandbox Code Playgroud)

这是附带的dart.html文件:

<!DOCTYPE html>

<html>
  <body>
     <p>x = {{ x }}</p>

     <ul>
       <template iterate='item in list'>
         <li>list item = {{item}}</li>
       </template>
     </ul>

     <ul>
       <template iterate='key in map.keys'>
         <li>map key = {{key}}, map value = {{map[key]}}</li>
       </template>
     </ul>

    <script type="application/dart" src="main.dart"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)