Вопрос

I'm trying to make a tree from a list of objects using templating, but I cannot get it to work. If there is a better way I am interested in it also.

It runs without error, but not showing anything.

Here is the html:

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <script src="packages/polymer/boot.js"></script>
  </head>
  <body>
   <ul>
    <template id="tmpl" repeat="{{ getRoot() }}">
     <li>{{ name }}
      <ul>
       <template ref="tmpl" repeat="{{ getChildren(name) }}"></template>
      </ul>
     </li>
    </template>    
   </ul>

  <script type="application/dart" src="test2.dart"\>

  </body>
 </html>

And the dart file:

import 'package:polymer/polymer.dart';

class Item extends ObservableBase {
  @observable String name;
  @observable List<String> children;
  @observable int level;

  Item(this.name, this.level, this.children);
}
@observable List<Item> items;

List<Item> getRoot(){
  return items.where((t) => t.level == 0);
}

List<Item> getChildren(String name){
  Item item = items.singleWhere((t) => t.name == name);
  return items.where((t) => item.children.contains(t.name));
}

main() {

 items = new List();

  items.add(new Item('Smurfs',0,['Smurf1','Smurf2']));
  items.add(new Item('Smurf1',1,[]));
  items.add(new Item('Smurf2',1,[]));

}

What am I doing wrong?

Thanks a lot

Это было полезно?

Решение

there are a few bugs here:

  • first, you don't instantiate your template. You must assign a model to a template element to do that
  • you must use PolymerExpressions binding delegate if you want to want to use functions in your binding expressions. This is default for polymer elements, but not for templates created manually
  • your filter functions do not return a List, but a WhereIterable
  • scopes are wrong. If you repeat over result of getRoot() function, the expectation is that getChildren(name) will be a member of Item

This should work better:

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

@observable List<Item> items;

class Item extends ObservableBase {
  @observable String name;
  @observable List<String> children;
  @observable int level;

  Item(this.name, this.level, this.children);

  List<Item> getChildren(String name){
    Item item = items.singleWhere((t) => t.name == name);
    return items.where((t) => item.children.contains(t.name)).toList();
  }
}

class MyModel extends ObservableBase {   
  List<Item> getRoot(){
    return items.where((t) => t.level == 0).toList();
  }    
}

main() {

  items = new List();
  items.add(new Item('Smurfs',0,['Smurf1','Smurf2']));
  items.add(new Item('Smurf1',1,[]));
  items.add(new Item('Smurf2',1,['Smurf3']));
  items.add(new Item('Smurf3',2,[]));

  TemplateElement templ = query("#tmpl");
  templ.bindingDelegate = new PolymerExpressions();
  MyModel m = new MyModel();
  templ.model = m;

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top