Populating derived fields in an Angular Dart component

前端 未结 2 1088
无人及你
无人及你 2021-01-20 12:56

I have a component that takes a single attribute. I want to populate a field in the component with a value that is derived from this attribute. I am running into the problem

2条回答
  •  孤城傲影
    2021-01-20 13:24

    The current best practice for derived fields is to calculate them on-demand and cache the results. By waiting, the app may be able to avoid unneeded work when the derived field isn't being used.

    e.g. your example component would look like:

    import 'package:angular/angular.dart';
    
    @NgComponent(
        selector: 'tokens',
        templateUrl: './component.html',
        cssUrl: './component.css',
        publishAs: 'ctrl',
        map: const {
          'text' : '@text'
        }
    )
    class TokensComponent {
      Map> _tokensCache = new Map>();
    
      String _text;
      get text => _text;
      set text(t) {
        _text = t;
        _tokensCache.clear();  // invalidate the cache any time text changes.
      }
    
      // Derived field.
      List get tokens =>
        text == null ? [] : _tokensCache.putIfAbsent(true,
            () => text.split('').map((char) =>  new Token(char, false)));
    
    }
    

    Now, tokens is always up-to-date, and if nothing ever asks for tokens, the component doesn't compute that field.

    In this example, the cache is required. Since Angular's dirty checking uses identical to check for changes, our component must return an identical tokens list if the component has not changed.

提交回复
热议问题