Pārlūkot izejas kodu

Merge pull request #29 from ryangjchandler/feature/off-listener

Feature/off listener
Ryan Chandler 5 gadi atpakaļ
vecāks
revīzija
e3c22e443f

+ 16 - 0
README.md

@@ -196,6 +196,22 @@ Spruce.on('init', ({ store }) => {
 })
 ```
 
+* `Spruce.off(eventName, callback)` - this can be used to unhook or de-register an event listener.
+
+```js
+var callback = () => {}
+
+Spruce.off('init', callback)
+```
+
+You can also unhook a listener using the function returned by `Spruce.on()`. This is especially useful for anonymous function callbacks.
+
+```js
+var off = Spruce.on('event', () => {})
+
+off()
+```
+
 * `Spruce.emit(eventName, data = {})` - this can be used to emit an event. The first argument should be the name of the event, the second should be an object containing data. This will be merged in with the core data, which consists of a `store` property. When emitting an event, a browser event will also be dispatched with a `spruce:` prefix.
 
 ```js

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.js


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.js.map


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.module.js


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.module.js.map


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.umd.js


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
dist/spruce.umd.js.map


+ 8 - 0
src/bus.js

@@ -9,6 +9,14 @@ export default {
         }
 
         this.events[name].push(callback)
+
+        return () => this.off(name, callback)
+    },
+
+    off(name, callback) {
+        this.events[name] = this.events[name].filter(registerCallback => {
+            return registerCallback !== callback
+        })
     },
 
     emit(name, data = {}) {

+ 5 - 1
src/index.js

@@ -69,7 +69,11 @@ const Spruce = {
     },
 
     on(name, callback) {
-        this.events.on(name, callback)
+        return this.events.on(name, callback)
+    },
+
+    off(name, callback) {
+        this.events.off(name, callback)
     },
 
     emit(name, data = {}) {

+ 30 - 0
tests/bus.spec.js

@@ -87,4 +87,34 @@ test('.watch() > can listen for changes to property', async () => {
 
     expect(fixture).toEqual('amazing')
     expect(oldFixture).toEqual('stuff')
+})
+
+test('.off() > can unregister listener', () => {
+    let fixture = undefined;
+
+    const callback = () => {
+        fixture = 0
+    }
+
+    Spruce.on('fixture-event', callback)
+    
+    Spruce.off('fixture-event', callback)
+
+    Spruce.emit('fixture-event')
+
+    expect(fixture).toBeUndefined()
+})
+
+test('.off() > returned when calling .on()', () => {
+    let fixture = undefined;
+
+    let off = Spruce.on('fixture-event', () => {
+        fixture = 0
+    })
+
+    off()
+
+    Spruce.emit('fixture-event')
+
+    expect(fixture).toBeUndefined()
 })

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels