Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Tweeted twitter.com/#!/StackCodeReview/status/428203945656590337
Source Link

Is this the right way to work with callbacks and the EventEmitter?

I'm creating a small online multiplayer game in NodeJS and I'm wondering if I'm "doing it right". Here is a bit of my code:

// app.js
// if I give an id as argument we assume it's an existing player.
var Player = new player();

Player.on('playerLoaded', function (err, result) {

    if (result) {

        Player.setName('somename');

        Player.on('setName', function (err, result) {

            console.log('Name changed');

        });

    } else {

        // couldn't load the player

    }

});

This is my player object:

function Player(id) {

    // if we don't have a id, this player needs to be created
    this.id = (typeof id !== 'number') ? this.createPlayer() : this.setPlayer(id);
    this.name = "";
    EventEmitter.call(this);

}

This is the createPlayer method:

Player.prototype.createPlayer = function () {

    var self = this;

    // we only need a datetime to insert
    connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {

        if (result) {

            process.nextTick(function () {

                if (result.insertId) {

                    console.log("Successfully found player no. " + result.insertId);

                    self.id = result.insertId;
    
                    // everything was successful
                    self.emit('playerLoaded', false, true);

                } else {

                    console.log("Trouble inserting a new player");

                    self.emit('playerLoaded', true, false);

                }

            });

        } else {

            process.nextTick(function () {

                console.log("Trouble with the mysql while inserting player: " + err);

                self.emit('playerLoaded', err, null);

            });

        }

    });

};

And this is the setName method:

Player.prototype.setName = function (name) {

    var self = this;

    connection.query("UPDATE players SET ? WHERE ?", [
        { name: name },
        { id: self.id }
    ], function (err, result) {

        if (result) {

            process.nextTick(function () {

                self.name = name;

                console.log("Successfully updated name of player no. " + self.id);

                self.emit('setName', false, true);

            });

        } else {

            process.nextTicket(function () {

                console.log("Trouble with the mysql while changing player name: " + err);

                self.emit('setName', err, false);

            });


        }

    });


};

Basically my question is if this is the right way to deal with callbacks?