te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Node.js make initialized object available in all modules - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js make initialized object available in all modules - Stack Overflow

programmeradmin3浏览0评论

I have an initialized object that I initialized in app.js file and I would like to make this initialized object is available in all modules. How could I do that? Passing this object to every modules is one way to do and I'm wondering if I'm missing anything or there should be done in difference ways?

I saw mongoose actually support default connection, which I need to init in app.js one time and anywhere in other modules, I can just simply use it without requiring passing it around. Is there any I can do the same like this?

I also checked global object doc from node.js .html, and wondering I should use global for issue.

Thanks

I have an initialized object that I initialized in app.js file and I would like to make this initialized object is available in all modules. How could I do that? Passing this object to every modules is one way to do and I'm wondering if I'm missing anything or there should be done in difference ways?

I saw mongoose actually support default connection, which I need to init in app.js one time and anywhere in other modules, I can just simply use it without requiring passing it around. Is there any I can do the same like this?

I also checked global object doc from node.js http://nodejs/api/globals.html, and wondering I should use global for issue.

Thanks

Share Improve this question asked Sep 6, 2013 at 3:19 Nam NguyenNam Nguyen 5,76014 gold badges59 silver badges73 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

A little advice:

  • You should only very rarely need to use a global. If you think you need one, you probably don't.
  • Singletons are usually an anti-pattern in Node.js, but sometimes (logging, config) they will get the job done just fine.
  • Passing something around is sometimes a useful and worthwhile pattern.

Here's an example of how you might use a singleton for logging:

lib/logger.js

var bunyan = require('bunyan'),
  mixIn = require('mout/object/mixIn'),

  // add some default options here...
  defaults = {},

  // singleton
  logger,

  createLogger = function createLogger(options) {
    var opts;

    if (logger) {
      return logger;
    }

    opts = mixIn({}, defaults, options);

    logger = bunyan.createLogger(opts);

    return logger;
  };

module.exports = createLogger;

lib/module.js

var logger = require('./logger.js'),
  log = logger();

log.info('Something happened.');

Hope that helps.

The solution, as you suggest is to add the object as a property to the global object. However, I would remend against doing this and placing the object in its own module that is required from every other module that needs it. You will gain benefits later on in several ways. For one, it is always explicit where this object es from and where it is initialized. You will never have a situation where you try to use the object before it is initialized (assuming that the module that defines it also initializes it). Also, this will help make your code more testable,

There are multiple solutions to the problem, depends upon how large your application is. The two solutions that you have mentioned are the most obvious ones. I would rather go for the third which is based on re-architecturing your code. The solution that I am providing looks alot like the executor pattern.

First create actions which require your mon module that are in this particular form -

var Action_One = function(monItems) {
    this.monItems = monItems;
};

Action_One.prototype.execute = function() {
    //..blah blah
    //Your action specific code
};


var Action_Two = function(monItems) {
    this.monItems = monItems;
};

Action_Two.prototype.execute = function() {
    //..blah blah
    //Your action_two specific code
};

Now create an action initializer which will programmatically initialize your actions like this -

var ActionInitializer = function(monItems) {
    this.monItems = monItems;
};

ActionInitializer.prototype.init = function(Action) {
    var obj = new Action(this.monItems);
    return obj;
};

Next step is to create an action executor -

//You can create a more plex executor using `Async` lib or something else
var Executor = function(ActionInitializer, monItems) {
    this.initializer = new ActionInitializer(monItems);
    this.actions = [];
};
//Use this to add an action to the executor
Executor.prototype.add = function(action) {
    var result = this.initializer.init(action);
    this.actions.push(result);
};
//Executes all the actions 
Executor.prototype.executeAll = function() {
    var result = [];
    for (var i = this.action.length - 1; i >= 0; i--) {
        result[i] = this.action[i].execute();
    }
    this.action = []
    return result;
};

The idea was to decouple every module so that there is only one module Executor in this case which is dependent on the mon properties. Now lets see how it would work -

var monProperties = {a:1, b:2};
//Pass the action initilizer class and the mon property object to just this one module
var e = new Executor(ActionInitializer, monProperties);
e.add(Action_One);
e.add(Action_Two);
e.executeAll();
console.log(e.results);

This way your program will be cleaner and more scalable. Shoot questions if it's not clear. Happy coding!

发布评论

评论列表(0)

  1. 暂无评论