简体   繁体   中英

Simple node.js module with init method

I'm trying to sort out a good simple pattern for node.js with an init method for the use of 'models' when connecting to mongodb collections. Basically, each collection has a 'model'.

Here's what I have, setup as a singleton, any reason not go to with this method or is there more recommended method within the context of node?

module.exports = User;

function User () {

  if ( arguments.callee.instance ) {
    return arguments.callee.instance;
  } else {
    arguments.callee.instance = this;
  }

  //Init our database collection

}

User.findOne = function (user_id) {

}

User.addUser = function () {

}

return new User();

Thank you!

Um, you should put User.prototype.method.

User.prototype.findOne = function (user_id) {

}

User.prototype.addUser = function () {

}

Instead of 'return new User()' you probably meant,

module.exports = new User();

One reason not to export a 'new' User() is if you want to create more than one user in your nodejs program. If you only have one user, then a singleton is fine. Also, if you want to pass data to this module, you may want to do so via a constructor argument, and if you only construct the User in the module, then you can't pass to the constructor in your app.

I use a pattern that assigns module.exports to a function. The first argument of all my exports is an object shared amongst all exports, so they can add events/listeners and talk to each other in various different ways.

For example ('events' and 'app' are psuedo, not based on any real API),

function doLogin(app) {
    return function (e) {
        // some code to do login
    }
}
module.exports = function login (app) {
    app.events.on('login', doLogin(app));
}

Now all of the other modules can trigger a login via

app.events.login({'user': '..','pass': '..'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM