Skip to content

Commit

Permalink
Ref generation for channel even handlers (phoenixframework#2429)
Browse files Browse the repository at this point in the history
* ref generation for channel even handlers

* onError and onClose to return ref
  • Loading branch information
youroff authored and chrismccord committed Aug 3, 2017
1 parent 1ca4d30 commit 26ceb6c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
32 changes: 28 additions & 4 deletions assets/js/phoenix.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ export class Channel {
this.params = params || {}
this.socket = socket
this.bindings = []
this.bindingRef = 0
this.timeout = this.socket.timeout
this.joinedOnce = false
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout)
Expand Down Expand Up @@ -386,15 +387,38 @@ export class Channel {
}
}

onClose(callback){ this.on(CHANNEL_EVENTS.close, callback) }
onClose(callback){
return this.on(CHANNEL_EVENTS.close, callback)
}

onError(callback){
this.on(CHANNEL_EVENTS.error, reason => callback(reason) )
return this.on(CHANNEL_EVENTS.error, reason => callback(reason))
}

on(event, callback){ this.bindings.push({event, callback}) }
/** Subscribes on channel events
*
* Subscription returnrs a ref counter, which can be used later to
* unsubsribe exact event listener:
*
* ```javascript
* ref1 = channel.on("event", do_stuff)
* ref2 = channel.on("event", do_other_stuff)
* channel.off("event", ref1)
* // Since unsubscription, do_stuff won't fire,
* // while do_other_stuff will keep firing on the "event"
* ```
*/
on(event, callback){
let ref = this.bindingRef++
this.bindings.push({event, ref, callback})
return ref
}

off(event){ this.bindings = this.bindings.filter( bind => bind.event !== event ) }
off(event, ref){
this.bindings = this.bindings.filter((bind) => {
return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref))
})
}

canPush(){ return this.socket.isConnected() && this.isJoined() }

Expand Down
20 changes: 20 additions & 0 deletions assets/test/channel_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,12 @@ describe("on", () => {

assert.ok(!ignoredSpy.called)
})

it("generates unique refs for callbacks", () => {
const ref1 = channel.on("event1", () => 0)
const ref2 = channel.on("event2", () => 0)
assert.equal(ref1 + 1, ref2)
})
})

describe("off", () => {
Expand Down Expand Up @@ -762,6 +768,20 @@ describe("off", () => {
assert.ok(!spy2.called)
assert.ok(spy3.called)
})

it("removes callback by its ref", () => {
const spy1 = sinon.spy()
const spy2 = sinon.spy()

const ref1 = channel.on("event", spy1)
const ref2 = channel.on("event", spy2)

channel.off("event", ref1)
channel.trigger("event", {}, defaultRef)

assert.ok(!spy1.called)
assert.ok(spy2.called)
})
})

describe("push", () => {
Expand Down

0 comments on commit 26ceb6c

Please sign in to comment.