@@ -47,31 +47,52 @@ export default function Bucket( name, storeProvider, channel ) {
4747 this . store = storeProvider ( this ) ;
4848 this . storeAPI = promiseAPI ( this . store ) ;
4949 this . isIndexing = false ;
50- this . channel = channel ;
5150
51+ /**
52+ * Listeners for channel events
53+ */
54+ this . onChannelIndex = this . emit . bind ( this , 'index' ) ;
55+ this . onChannelError = this . emit . bind ( this , 'error' ) ;
56+ this . onChannelUpdate = ( id , data ) => {
57+ this . update ( id , data , { sync : false } ) ;
58+ } ;
59+
60+ this . onChannelIndexingStateChange = ( isIndexing ) => {
61+ this . isIndexing = isIndexing ;
62+ if ( isIndexing ) {
63+ this . emit ( 'indexing' ) ;
64+ }
65+ } ;
66+
67+ this . onChannelRemove = ( id ) => this . remove ( id ) ;
68+
69+ if ( channel ) {
70+ this . setChannel ( channel ) ;
71+ }
72+ }
73+
74+ inherits ( Bucket , EventEmitter ) ;
75+
76+ Bucket . prototype . setChannel = function ( channel ) {
77+ if ( this . channel ) {
78+ this . channel
79+ . removeListener ( 'index' , this . onChannelIndex )
80+ . removeListener ( 'error' , this . onChannelError )
81+ . removeListener ( 'update' , this . onChannelUpdate )
82+ . removeListener ( 'indexingStateChange' , this . onChannelIndexingStateChange )
83+ . removeListener ( 'remove' , this . onChannelRemove ) ;
84+ }
85+ this . channel = channel ;
5286 channel
5387 // forward the index and error events from the channel
54- . on ( 'index' , ( ... args ) => this . emit ( 'index' , ... args ) )
55- . on ( 'error' , ( ... args ) => this . emit ( 'error' , ... args ) )
88+ . on ( 'index' , this . onChannelIndex )
89+ . on ( 'error' , this . onChannelError )
5690 // when the channel updates or removes data, the bucket should apply
5791 // the same updates
58- . on ( 'update' , ( id , data ) => {
59- this . update ( id , data , { sync : false } ) ;
60- } )
61- . on ( 'indexingStateChange' , ( isIndexing ) => {
62- this . isIndexing = isIndexing ;
63- if ( isIndexing ) {
64- this . emit ( 'indexing' ) ;
65- }
66- } )
67- . on ( 'remove' , ( id ) => {
68- // TODO, there needs te be a way to remove without telling the
69- // channel to do it
70- this . remove ( id ) ;
71- } ) ;
72- }
73-
74- inherits ( Bucket , EventEmitter ) ;
92+ . on ( 'update' , this . onChannelUpdate )
93+ . on ( 'indexingStateChange' , this . onChannelIndexingStateChange )
94+ . on ( 'remove' , this . onChannelRemove ) ;
95+ } ;
7596
7697Bucket . prototype . reload = function ( ) {
7798 this . channel . reload ( ) ;
0 commit comments