@@ -30,7 +30,7 @@ class Store {
3030 this . _dispatching = false
3131 this . _rootMutations = this . _mutations = mutations
3232 this . _modules = modules
33- this . _events = Object . create ( null )
33+ this . _subscribers = [ ]
3434 // bind dispatch to self
3535 const dispatch = this . dispatch
3636 this . dispatch = ( ...args ) => {
@@ -127,7 +127,7 @@ class Store {
127127 const mutation = isObjectStyleDispatch
128128 ? payload
129129 : { type, payload }
130- this . emit ( 'mutation' , mutation , state )
130+ this . _subscribers . forEach ( sub => sub ( mutation , state ) )
131131 }
132132 } else {
133133 console . warn ( `[vuex] Unknown mutation: ${ type } ` )
@@ -152,6 +152,23 @@ class Store {
152152 return this . _vm . $watch ( ( ) => fn ( this . state ) , cb , options )
153153 }
154154
155+ /**
156+ * Subscribe to state changes. Fires after every mutation.
157+ */
158+
159+ subscribe ( fn ) {
160+ const subs = this . _subscribers
161+ if ( subs . indexOf ( fn ) < 0 ) {
162+ subs . push ( fn )
163+ }
164+ return ( ) => {
165+ const i = subs . indexOf ( fn )
166+ if ( i > - 1 ) {
167+ subs . splice ( i , 1 )
168+ }
169+ }
170+ }
171+
155172 /**
156173 * Hot update mutations & modules.
157174 *
@@ -274,10 +291,6 @@ function install (_Vue) {
274291 return
275292 }
276293 Vue = _Vue
277- // reuse Vue's event system
278- ; [ 'on' , 'off' , 'once' , 'emit' ] . forEach ( e => {
279- Store . prototype [ e ] = Store . prototype [ '$' + e ] = Vue . prototype [ '$' + e ]
280- } )
281294 override ( Vue )
282295}
283296
0 commit comments