diff --git a/modules/angular2/src/core/change_detection/pipe_transform.ts b/modules/angular2/src/core/change_detection/pipe_transform.ts index 5c4cb2a4df..975c44b289 100644 --- a/modules/angular2/src/core/change_detection/pipe_transform.ts +++ b/modules/angular2/src/core/change_detection/pipe_transform.ts @@ -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; }