发出自定义事件

时间:2014-04-01 09:17:03

标签: javascript node.js yeoman bower yeoman-generator

我在我的一个nodejs模块中使用我的自定义yeoman生成器programmatical。我编写了一个适配器来替换默认的TerminalAdapter。 问题是,

  
      
  • 当我使用emit方法触发自定义事件时,我无法做到   在我的模块中监听该事件。它没有被解雇。
  •   
  • 即使end事件监听器也没有被解雇。
  •   

请告诉我这里缺少的东西,

以下是我的模块代码

'use strict';
var fs = require('fs');
var path = require('path');
var MyOwnAdapter = require('./MyOwnAdapter');
var adapt = new MyOwnAdapter();
var env = require('./generator-myframewrk/node_modules/yeoman-generator')(null, {}, adapt);

env.register(path.resolve(__dirname, './generator-myframewrk'), 'myframewrk');
exports.run = function (options, answers) {
    var obj = {};
    adapt.setAnswers(answers);
    process.chdir(options.projdir);

    env.on("end", function(){
        this.log("Even this is not getting called !!!"); //not coming here
    }.bind(this));

    env.on("alldone", function(){
        this.log("Everything is done (including Bower install)");  //not coming here
        obj.cb();
    }.bind(this));

    env.run('myframewrk', function(){
        this.log('ran yo myframewrk, But bower install might be pending'); //coming here
    });

    return {
        done: function (cb) {
            obj.cb = cb;
        }
    };
};

下面是我的生成器代码,

var MyframewrkGenerator = yeoman.generators.Base.extend({
    init: function () {
        this.pkg = require('../package.json');

        this.on('end', function () {
            if (!this.options['skip-install']) {
                this._installBower();
            }
        });
    },

    _installBower: function () {
        this.log("Running bower install...");
        /*reads bower.json and installs*/
        bower.commands.install([], {}, {directory : "./"}).on('error', function (error) {
            this.log("BOWER error::");
            this.log(JSON.stringify(error));
        }.bind(this)).on('log', function (log) {
            this.log("BOWER LOG::"); // coming here
        }.bind(this)).on('end', function (installed) {
            this.log("BOWER END::"); // coming here
            this.emit("alldone");   // my custom event
        }.bind(this));
    },

    askFor: function () { ...

1 个答案:

答案 0 :(得分:0)

我从_installBower中取出了this.on('end', function () {});方法并将其作为单独的异步函数。这很好用。我不再需要自定义活动了!

Thx ...

bowerInstallHelper: function(){
        if (!this.options['skip-install']) {
            var cb = this.async();
            this._installBower(cb);
        }
    }