import Dep , { clearTarget , setTarget } from './deps' ; import { Sub } from '../types/observer' ; import { queueWatcher } from './scheduler' ; import { isArray , isFunc } from '../utils/typeOf' ; import { State } from '../types/store' ; import { getState } from '../store' ; export default class Watcher { state : State ; watcher : Sub ; constructor ( watcher , state ) { this . watcher = watcher ; this . state = state ; setTarget ( this ) ; this . getter ( ) ; } getter ( ) { const val = this . watcher . call ( this . state ) ; if ( isFunc ( val ) ) this . watcher = val ; clearTarget ( ) ; } update ( ) { queueWatcher ( this ) ; } addDep ( dep ) { dep . addSub ( this ) ; } } function watch < T > ( sub , state ) { new Watcher ( sub , state ) ; } export function addWatch < T > ( subs ) { const state = getState ( ) ; if ( isArray ( subs ) ) { subs . forEach ( ( sub ) => watch ( sub , state ) ) ; } else { watch ( subs , state ) ; } }