Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'phát triển javascript - part 41', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 14.5 Event Emitters 373 Listing 14.54 Expecting chatRoom to be event emitter testCase exports chatRoom should be event emitter function test test.isFunction chatRoom.addListener test.isFunction chatRoom.emit test.done We can pass this test by popping EventEmitter.prototype in as chatRoom s prototype as seen in Listing 14.55. Listing 14.55 chatRoom inheriting from EventEmitter.prototype . var EventEmitter require events .EventEmitter . var chatRoom Object.create EventEmitter.prototype chatRoom.addMessage function user message . chatRoom.getMessagesSince function id . Note that because V8 fully supports ECMAScript 5 s Object.create we could have used property descriptors to add the methods as well as seen in Listing 14.56. Listing 14.56 chatRoom defined with property descriptors var chatRoom Object.create EventEmitter.prototype addMessage value function user message . getMessagesSince value function id . Download from www.eBookTM.com 374 Server-Side JavaScript with Node.js At this point the property descriptors don t provide anything we have a documented need for i.e. the ability to override default property attribute values so we ll avoid the added indentation and stick with the simple assignments in Listing 14.55. Next up we make sure that addMessage emits an event. Listing 14.57 shows the test. Listing 14.57 Expecting addMessage to emit a message event testCase exports chatRoom.addMessage . should emit message event function test var message this.room.addListener message function m message m this.room.addMessage cjno msg .then function m test.same m message test.done To pass this test we need to place a call to emit right before we resolve the promise as seen in Listing 14.58. Listing 14.58 Emitting a message event chatRoom.addMessage function user message callback var promise new Promise process.nextTick function . if err . this.emit message data promise.resolve data else promise.reject err true Download from www.eBookTM.com 14.5 Event Emitters 375 .bind this .