3

我有一个带有单个属性的组件。我想用派生自该属性的值填充组件中的字段。我遇到的问题是,当构造函数内的代码运行时,没有发生与属性的绑定。那么,如何设置派生字段的值呢?

这是一些代码:

import 'package:angular/angular.dart';

@NgComponent(
    selector: 'tokens',
    templateUrl: './component.html',
    cssUrl: './component.css',
    publishAs: 'ctrl',
    map: const {
      'text' : '@text'
    }
)
class TokensComponent {
  String text;

  // Derived field.
  List<Token> tokens = new List<Token>();

  TokensComponent() {
    print('inside constructor, text = $text'); // $text is null.
  }

}

class Token {
  String char;
  bool important;
  Token(this.char, this.important);
}
4

2 回答 2

3

一种可能的解决方案是让组件实现NgAttachAware并定义attach()方法。然后可以在内部设置派生字段的值attach()。我不知道是否有更惯用的方法来做到这一点,但使用attach()似乎有效。

这是代码:

import 'package:angular/angular.dart';

@NgComponent(
    selector: 'tokens',
    templateUrl: './component.html',
    cssUrl: './component.css',
    publishAs: 'ctrl',
    map: const {
      'text' : '@text'
    }
)
class TokensComponent implements NgAttachAware {
  String text;

  // Derived field.
  List<Token> tokens = new List<Token>();

  TokensComponent() {
    print('inside constructor, text = $text');
  }

  void attach() {
    print('inside attach(), text = $text'); // $text is no longer null.
    text.split('').forEach((char) => tokens.add(new Token(char, false)));
  }
}

class Token {
  String char;
  bool important;
  Token(this.char, this.important);
}
于 2014-01-12T22:01:06.803 回答
3

当前派生字段的最佳实践是按需计算它们并缓存结果。通过等待,当派生字段未被使用时,应用程序可能能够避免不必要的工作。

例如,您的示例组件如下所示:

import 'package:angular/angular.dart';

@NgComponent(
    selector: 'tokens',
    templateUrl: './component.html',
    cssUrl: './component.css',
    publishAs: 'ctrl',
    map: const {
      'text' : '@text'
    }
)
class TokensComponent {
  Map<bool, List<Token>> _tokensCache = new Map<bool, List<Token>>();

  String _text;
  get text => _text;
  set text(t) {
    _text = t;
    _tokensCache.clear();  // invalidate the cache any time text changes.
  }

  // Derived field.
  List<Token> get tokens =>
    text == null ? [] : _tokensCache.putIfAbsent(true,
        () => text.split('').map((char) =>  new Token(char, false)));

}

现在,令牌始终是最新的,如果没有人要求令牌,则组件不会计算该字段。

在此示例中,缓存是必需的。由于 Angular 的脏检查用于identical检查更改,如果组件没有更改,我们的组件必须返回相同的标记列表。

于 2014-01-12T23:22:59.643 回答