Skip to content

Commit

Permalink
[CB-633] Fix for channel, regarding unsubscribing and how a handler c…
Browse files Browse the repository at this point in the history
…ount is decremented. Also added tests to catch this.
  • Loading branch information
filmaj committed May 8, 2012
1 parent 8b36951 commit 6cb6e6c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
11 changes: 7 additions & 4 deletions lib/common/channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,13 @@ Channel.prototype.unsubscribe = function(g) {
if (g === null || g === undefined) { throw "You must pass _something_ into Channel.unsubscribe"; }

if (typeof g == 'function') { g = g.observer_guid; }
this.handlers[g] = null;
delete this.handlers[g];
this.numHandlers--;
if (this.events.onUnsubscribe) this.events.onUnsubscribe.call(this);
var handler = this.handlers[g];
if (handler) {
this.handlers[g] = null;
delete this.handlers[g];
this.numHandlers--;
if (this.events.onUnsubscribe) this.events.onUnsubscribe.call(this);
}
};

/**
Expand Down
32 changes: 26 additions & 6 deletions test/test.channel.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
describe("channel", function () {
var channel = require('cordova/channel');
var channel = require('cordova/channel'),
c;

describe("when subscribing", function() {
beforeEach(function() {
c = null;
c = channel.create('masterexploder');
});

describe("subscribe method", function() {
it("should throw an exception if no function is provided", function() {
var c = channel.create('test');
expect(function() {
c.subscribe();
}).toThrow();
Expand All @@ -21,7 +26,6 @@ describe("channel", function () {
}).toThrow();
});
it("should not change number of handlers if no function is provided", function() {
var c = channel.create('heydawg');
var initialLength = c.numHandlers;

try {
Expand All @@ -38,9 +42,25 @@ describe("channel", function () {
});
});

describe("when unsubscribing", function() {
describe("unsubscribe method", function() {
it("should throw an exception if passed in null or undefined", function() {
expect(function() {
c.unsubscribe();
}).toThrow();
expect(function() {
c.unsubscribe(null);
}).toThrow();
});
it("should not decrement numHandlers if unsubscribing something that does not exist", function() {
var initialLength = c.numHandlers;
c.unsubscribe('blah');
expect(c.numHandlers).toEqual(initialLength);
c.unsubscribe(2);
expect(c.numHandlers).toEqual(initialLength);
c.unsubscribe({balls:false});
expect(c.numHandlers).toEqual(initialLength);
});
it("should change the handlers length appropriately", function() {
var c = channel.create('test');
var firstHandler = function() {};
var secondHandler = function() {};
var thirdHandler = function() {};
Expand Down

0 comments on commit 6cb6e6c

Please sign in to comment.