import { Reference } from "./reference" ; import { PersistenceError } from "./persistenceError" ; hidden export class Observer { private _watching : any [ ] = [ ] ; private _onChange : ( changes : ObjectChangeInfo [ ] ) => void ; param callback constructor ( callback ) { this . _onChange = this . _createOnChangeEvent ( callback ) ; } watch ( obj ) { if ( ! this . _watching ) throw new PersistenceError ( "Observer is destroyed." ) ; Object . observe ( obj , this . _onChange ) ; this . _watching . push ( obj ) ; } destroy ( ) { if ( ! this . _watching ) return ; for ( var i = 0 ; i < this . _watching . length ; i ++ ) { Object . unobserve ( this . _watching [ i ] , this . _onChange ) ; } this . _watching = undefined ; } private _createOnChangeEvent ( callback ) { return ( changes ) => { for ( var i = 0 ; i < changes . length ; i ++ ) { var change = changes [ i ] ; if ( change . type != 'update' || ! Reference . areEqual ( change . oldValue , ( < any > change . object ) [ change . name ] ) ) { callback ( ) ; this . destroy ( ) ; return ; } } } ; } }