码迷,mamicode.com
首页 > 其他好文 > 详细

Pomelo的component组件

时间:2014-09-30 00:24:21      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   使用   ar   java   for   文件   div   

  pomelo的核心是由一系列松耦合的component组成,同时我们也可以实现我们自己的component来完成一些自己定制的功能。对于我们的聊天应用,我们尝试给其增加一个component,目的是展示如何增加一个component,以及component的生命周期管理,而不会特别关注这个component的实际功能。我们现在就给其增加一个component HelloWorld,这个component仅仅在master服务器上加载运行,在master服务器的话,它将每隔一段时间在console上打印出来一个HelloWorld,具体的时间间隔由opts配置来指定

  在app下建立components/HelloWorld.js文件, 大致代码如下:

module.exports = function(app, opts) {
  return new HelloWorld(app, opts);
};

var DEFAULT_INTERVAL = 3000;

var HelloWorld = function(app, opts) {
  this.app = app;
  this.interval = opts.interval | DEFAULT_INTERVAL;
  this.timerId = null;
};

HelloWorld.name = ‘__HelloWorld__‘;

HelloWorld.prototype.start = function(cb) {
  console.log(‘Hello World Start‘);
  var self = this;
  this.timerId = setInterval(function() {
    console.log(self.app.getServerId() + ": Hello World!");
    }, this.interval);
  process.nextTick(cb);
}

HelloWorld.prototype.afterStart = function (cb) {
  console.log(‘Hello World afterStart‘);
  process.nextTick(cb);
}

HelloWorld.prototype.stop = function(force, cb) {
  cosole.log(‘Hello World stop‘);
  clearInterval(this.timerId);
  process.nextTick(cb);
}

  我们看到每一个component一般都要定义start,afterStart,stop这些hook函数,供pomelo管理其生命周期时进行调用。对于component的启动,pomelo总是先调用其加载的每一个component提供的start函数,当全部调用完后,才会去调用其加载的每一个component的afterStart方法,这里总是按顺序调用的。因为调用afterStart的时候,所有component的start已经调用完毕,可以添加一些需要全局就绪的工作。stop用于程序结束时对component进行清理时使用

  在app.js配置如下:

// app.js
var helloWorld = require(‘./app/components/HelloWorld‘);

app.configure(‘production|development‘, ‘master‘, function() {
  app.load(helloWorld, {interval: 5000});
});

  

Pomelo的component组件

标签:blog   io   os   使用   ar   java   for   文件   div   

原文地址:http://www.cnblogs.com/fuland/p/4001063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!