Inquirer.js:允许用户编写列表响应

时间:2015-03-25 21:05:45

标签: yeoman

好吧,我发现了一个自制发电机。我有一个提示,列出了三个不同的选项供您选择。它看起来像这样:

JS文件的名称: - 一个 - 两个 - 其他

我希望第三个允许该选项允许用户自己编写。 Mabye我可以调用另一个提示方法吗?



// ****************************************************************************
// Author: Daniel Jenkins
// Date: 03/35/3015
// Purpose: A generator for creating js files including, name, date, and purpose fields.
// ****************************************************************************

var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  prompting: function() {
    var done = this.async();
    var myChoices = [this.appname, 'one', 'two', 'other'];
    var prompts = {
      type: 'list',
      name: 'fileName',
      message: 'Name of new JS file: ',
      choices: myChoices
    };

    // Select the filename from list.
    this.prompt(prompts, function(answers) {

      // Store user input as an argument for the EJS preprossor.
      this.context = {
        fileName: answers.fileName,
      };

      done();
    }.bind(this));
  },

  // Add file after filling in EJS template 
  copyMainFiles: function() {

    // Create a time object for todays date.
    var my_date = new Date();

    // Add date property. 
    this.context.fileDate = my_date.toDateString();

    // Run through EJS and create the file.
    this.template("_index.js", this.context.fileName + ".js", this.context);
  }
});




1 个答案:

答案 0 :(得分:1)

您可以使用when,通过运行条件语句来指定另一个字段。如果语句返回true,则将调用该字段,否则将跳过该字段。

请参阅代码添加内容:

module.exports = generators.Base.extend( {
    prompting : function () {
        var done = this.async();
        var myChoices = [ this.appname, 'one', 'two', 'other' ];
        var prompts = [ {
            type    : 'list',
            name    : 'fileName',
            message : 'Name of new JS file: ',
            choices : myChoices
        },{
            when    : function ( answers ) {
                return answers.fileName === 'other';
            },
            type    : 'input',
            name    : 'fileName',
            message : 'custom file name'
        }];

        // Select the filename from list.
        this.prompt( prompts, function ( answers ) {

            // Store user input as an argument for the EJS preprossor.
            this.context = {
                fileName : answers.fileName,
            };

            done();
        }.bind( this ) );
    },

    // Add file after filling in EJS template 
    copyMainFiles : function () {

        // Create a time object for todays date.
        var my_date = new Date();

        // Add date property. 
        this.context.fileDate = my_date.toDateString();

        // Run through EJS and create the file.
        this.template( "_index.js", this.context.fileName + ".js", this.context );
    }
} );