madduci
madduci

Reputation: 2893

Coffeescript class method always returns false

I'm dealing with a simple Coffescript class representing a Database module (using SQLite with jugglingdb, which works fine), which has a method that returns always false and I can't figure out why is that:

database.coffee

Schema = require('jugglingdb').Schema;

module.exports = class Database
  constructor: (database_file) ->
    if database_file?
        @filename = database_file
    else
        @filename = 'board.db'

    console.log '[DB] SQLite database: ' + @filename

    @db = null
    @connection = false

  connect: (callback) ->
    @db = new Schema 'sqlite3', { database: @filename } 
    @db.on 'connected', () -> 
        console.log '[DB] Database connection established'
        @connection = true
        callback? callback(@connection)
    @db.on 'disconnected', ()-> 
        console.log '[DB] Database closed' 
        @connection = false
        callback? callback(@connection)
    @db.log = (message, duration)-> console.log '[DB]' + message


  close: ->
    @db.disconnect()
    delete @db
    @db = null

  getSchema: ->
    if @db isnt null
        return @db
    else
        return null

  isConnected: -> 
    return @connection

database-test.js

var Database = require('./database');
function db_connection_cb(is_connected)
{
  var connection = db.isConnected();
  console.log("Class method: " + connection + " --- from callback: " + is_connected);
}

var db = new Database('user_test.db'); 
db.connect(db_connection_cb);

surprisingly, db.isConnected() reports always false, but is_connected is always true. Why Node.js is having such a strange behaviour?

Upvotes: 0

Views: 64

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

The main problem is that you're loosing this context in @db.on callbacks. To prevent it you should use fat arrow => instead of ->.

The way you're calling callback function as always wrong, the right syntax for conditional call is callback? @connection.

Here is how your code should've looked:

@db.on 'connected', => 
    console.log '[DB] Database connection established'
    @connection = true
    callback? @connection
@db.on 'disconnected', => 
    console.log '[DB] Database closed' 
    @connection = false
    callback? @connection

Upvotes: 2

Related Questions