0

I'm creating an observable pattern in node like this.

./tableEvents.model.js

var EventEmitter = require('events').EventEmitter;
var util = require('util');

module.exports = function(logger){

    function TableEvent(tableId){
        this.tableId = tableId;
        EventEmitter.call(this);
    }

    TableEvent.prototype.startTimer = function(){
        this.timer = setTimeout(function(){
            console.log('been 5 seconds, destroying');
            this.emit('destroy');
        }, 5000);
    };

    util.inherits(TableEvent, EventEmitter);

    return TableEvent;

};

Then in my route.js file

var TableEvent = require('../models/tableEvents.model')(logger);

var tableEvent = new TableEvent(table._id);

tableEvent.startTimer();

tableEvent.on('destroy', function(){
    console.log('destroyed');
    clearInterval(tableEvent.timer);
});

Now when it tries to tableEvent.startTimer(); I get this error in console

tableEvent.startTimer is not a function

Why is this?

Garuuk
  • 2,153
  • 6
  • 30
  • 59
  • When you have fixed the prototype overwriting, notice that [the `this` in the `setTimeout` callback won't work](http://stackoverflow.com/q/20279484/1048572) – Bergi Apr 04 '16 at 20:07
  • Thanks, I added var self = this; – Garuuk Apr 04 '16 at 20:33

1 Answers1

3

util.inherits() overwrites the prototype of the inheriting object/constructor in order to accomplish its task. You need to make your prototype changes only after calling util.inherits():

function TableEvent(tableId){
    this.tableId = tableId;
    EventEmitter.call(this);
}

util.inherits(TableEvent, EventEmitter);

TableEvent.prototype.startTimer = function(){
    this.timer = setTimeout(function(){
        console.log('been 5 seconds, destroying');
        this.emit('destroy');
    }, 5000);
};
mscdex
  • 104,356
  • 15
  • 192
  • 153