Skip to content

Commit

Permalink
'message' listener removed after message sent
Browse files Browse the repository at this point in the history
  • Loading branch information
oveddan committed Apr 30, 2012
1 parent 8e5afa4 commit c84cb2e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions chapp/chat_room.js
Expand Up @@ -23,6 +23,8 @@ chatRoom.addMessage = function(user, message){
data = {id : id++, user : user, message : message};
this.messages.push(data);
this.emit('message', data);
if(this.waitForMessagesSinceListener)
this.removeListener('message', this.waitForMessagesSinceListener);
promise.resolve(data);
} else
promise.reject(err, true);
Expand Down Expand Up @@ -51,9 +53,10 @@ chatRoom.waitForMessagesSince = function(id){
if(messages.length > 0){
promise.resolve(messages);
} else {
this.addListener('message', function(message) {
this.waitForMessagesSinceListener = function(message) {
promise.resolve([message]);
});
};
this.addListener('message', this.waitForMessagesSinceListener);
}
}.bind(this));

Expand Down
15 changes: 15 additions & 0 deletions test/chat_room_tests.js
Expand Up @@ -205,4 +205,19 @@ suite('chatRoom.waitForMessagesSince', function(){
this.room.addMessage(user, msg);
}.bind(this));
});
test("new 'message' listener should be removed after message sent", function(done){
var user = 'cjno',
msg = 'Are you waiting for this?';

var originalListenersLength = this.room.listeners('message').length;

this.room.waitForMessagesSince(0).then(function(msgs){
assert.equal(this.room.listeners('message').length, originalListenersLength);
done();
}.bind(this));

process.nextTick(function(){
this.room.addMessage(user, msg);
}.bind(this));
});
});

0 comments on commit c84cb2e

Please sign in to comment.