docs(core): add docs for PipeOnDestroy interface

This commit is contained in:
Jeff Cross 2015-09-15 10:22:12 -07:00 committed by Igor Minar
parent d9776b4112
commit d276370ba1
1 changed files with 43 additions and 14 deletions

View File

@ -35,24 +35,53 @@
export interface PipeTransform { transform(value: any, args: any[]): any; }
/**
* An interface that stateful pipes should implement.
* To create a stateful Pipe, you should implement this interface.
*
* #Example
* A stateful pipe may produce different output, given the same input. It is
* likely that a stateful pipe may contain state that should be cleaned up when
* a binding is destroyed. For example, a subscription to a stream of data may need to
* be disposed, or an interval may need to be cleared.
*
* ## Example
*
* In this example, a pipe is created to countdown its input value, updating it every
* 50ms. Because it maintains an internal interval, it automatically clears
* the interval when the binding is destroyed or the countdown completes.
*
* ```
* class StatefulPipe implements PipeTransform, PipeOnDestroy {
* connection;
*
* onDestroy() {
* this.connection.release();
* }
*
* transform(value, args = []) {
* this.connection = createConnection();
* // ...
* return someValue;
* }
* import {Pipe, PipeTransform} from 'angular2/angular2'
* @Pipe({name: 'countdown'})
* class CountDown implements PipeTransform, PipeOnDestroy {
* remainingTime:Number;
* interval:SetInterval;
* onDestroy() {
* if (this.interval) {
* clearInterval(this.interval);
* }
* }
* transform(value: any, args: any[] = []) {
* if (!parseInt(value, 10)) return null;
* if (typeof this.remainingTime !== 'number') {
* this.remainingTime = parseInt(value, 10);
* }
* if (!this.interval) {
* this.interval = setInterval(() => {
* this.remainingTime-=50;
* if (this.remainingTime <= 0) {
* this.remainingTime = 0;
* clearInterval(this.interval);
* delete this.interval;
* }
* }, 50);
* }
* return this.remainingTime;
* }
* }
* ```
*
* Invoking `{{ 10000 | countdown }}` would cause the value to be decremented by 50,
* every 50ms, until it reaches 0.
*
* See full working example: http://plnkr.co/edit/hlaejwQAmWayxwc5YXQE?p=preview
*/
export interface PipeOnDestroy { onDestroy(): void; }