• Pomelo的component组件


      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});
    });
    

      

  • 相关阅读:
    Google
    LeetCode 664. 奇怪的打印机
    LeetCode 79. 单词搜索
    LeetCode 224. 基本计算器
    Windows 端口映射
    LeetCode 354. 俄罗斯套娃信封问题
    LeetCode 300. 最长递增子序列
    LeetCode 338. 比特位计数
    LeetCode 395. 至少有K个重复的最长子串
    LeetCode 424. 替换后的最长重复字符
  • 原文地址:https://www.cnblogs.com/fuland/p/4001063.html
Copyright © 2020-2023  润新知