n S c o p e ( ) { t h i s . $ i d = n e x t U i d ( ) t h i s . $ $ w a t c h e r s = [ ] } v a r $ r o o t S c o p e = n e w S c o p e ( ) That's all there is to it! PS All code is extremely simplified
p r o t o t y p e . $ n e w = f u n c t i o n ( ) { v a r C h i l d = f u n c t i o n ( ) { } C h i l d . p r o t o t y p e = t h i s c h i l d = n e w C h i l d ( ) c h i l d . $ p a r e n t = t h i s r e t u r n c h i l d }
c o p e . p r o t o t y p e . $ w a t c h = f u n c t i o n ( w a t c h E x p , l i s t e n e r ) { t h i s . $ $ w a t c h e r s . p u s h ( { f n : l i s t e n e r , e x p : w a t c h E x p } ) } There is also $ w a t c h C o l l e c t i o n
f u n c t i o n ( ) { / / f o r t h i s s c o p e a n d a l l i t s c h i l d r e n , / / g o t h r o u g h a l l w a t c h e r s a n d / / c o m p a r e t o t h e i r l a s t v a l u e f o r ( s c o p e i n [ t h i s , * c h i l d r e n S c o p e s ] ) { f o r ( w a t c h i n s c o p e . $ $ w a t c h e r s ) { i f ( w a t c h . e x p ( ) ! = = w a t c h . l a s t ) { d i r t y = t r u e w a t c h . l a s t = w a t c h . e x p ( ) w a t c h . f n ( ) } } } }
f u n c t i o n ( ) { d o { w h i l e ( t h i s . $ $ a s y n c Q u e u e . l e n g t h ) { a s y n c T a s k = t h i s . $ $ a s y n c Q u e u e . s h i f t ( ) a s y n c T a s k . s c o p e . $ e v a l ( a s y n c T a s k . e x p r e s s i o n ) } f o r ( s c o p e i n [ t h i s , * c h i l d r e n S c o p e s ] ) { f o r ( w a t c h i n s c o p e . $ $ w a t c h e r s ) { i f ( w a t c h . g e t ( ) ! = = w a t c h . l a s t ) { d i r t y = t r u e w a t c h . l a s t = w a t c h . g e t ( ) } } } } w h i l e ( d i r t y | | a s y n c Q u e u e . l e n g t h ) }
n t i m e o u t ( f n , d e l a y ) { s e t T i m e o u t ( f u n c t i o n ( ) { f n ( ) $ r o o t S c o p e . $ a p p l y ( ) } , d e l a y ) } Run function and then a full $apply phase
n g ( ) / / U S U A L L Y B A D $ t i m e o u t ( f u n c t i o n ( ) { d o S o m e t h i n g A l m o s t R i g h t A w a y ( ) } ) / / G O O D $ s c o p e . $ e v a l A s y n c ( f u n c t i o n ( ) { d o S o m e t h i n g A l m o s t R i g h t A w a y ( ) } ) Runs during a $digest phase
know if running within a $digest phase / / B A D d o S o m e t h i n g ( ) $ r o o t S c o p e . $ a p p l y ( ) u n l e s s $ r o o t S c o p e . $ $ p h a s e / / G O O D $ s c o p e . $ e v a l A s y n c ( d o S o m e t h i n g ) This schedules a $digest phase if one isn't running
for $apply: $ a p p l y : f u n c t i o n ( e x p r ) { t h i s . $ e v a l ( e x p r ) $ r o o t S c o p e . $ d i g e s t ( ) } Running $apply on ANY scope will trigger a $digest phase on ALL scopes. If you need to dirty check only one scope, run digest on it manually: $ s c o p e . $ d i g e s t ( )