Question

I'm using expressjs along with nowjs, I'm binding some events to the now object right inside the route when it's being accessed. This isn't very clean, and I have the feeling everything the root is accessed the events are executed.

I'm not sure how, but I wonder if I could move this elsewhere?

app.get('/room/:name', function(req, res)
{
  //Should this code be moved elsewhere?... how?
  nowjs.on('connect', function()
  {
    this.now.room = req.params.name;
    nowjs.getGroup(this.now.room).addUser(this.user.clientId);
    console.log("Joined: " + this.now.name);
  });

  everyone.now.distributeMessage = function(message){
    nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
  };

  res.render('room', { user : user });
});
Was it helpful?

Solution

You could separate the room code out into another module, perhaps even applying a pattern such as MVC to your app.

var Room = require('./models/room');

...

app.get('/room/:name', function(req, res) {
  Room.initialize(params.name);
  res.render('room', {user: user});
});

// models/room.js

Room = {
  initialize: function(name) {
    nowjs.on('connect', function() {
      this.now.room = name;
      nowjs.getGroup(this.now.room).addUser(this.user.clientId);
      console.log("Joined: " + this.now.name);
    });

    everyone.now.distributeMessage = function(message){
      nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
    };
  }
};

module.exports = Room; // makes `require('this_file')` return Room

I'm not super familiar with Now.js, but you get the idea--but the code that doesn't concern the HTTP stack in another module, in another file, and require it and use it when necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top