修改现有代码以接受多个参数

时间:2017-03-17 20:18:58

标签: javascript

请参阅以下代码以获取以下问题描述:

// Populate a select list with pt codes.
    this.populateCodeList = function (ptName_, listSelector_) {

        if (!ptName_) { return self.displayError("Invalid pt name", "populatecodeList"); }
        if (!listSelector_) { return self.displayError("Invalid list selector", "populatecodeList"); }

        var pt = self.registry.pt[ptName_];

        if (!pt) { return self.displayError("Invalid PT: " + ptName_, "populateCodeList"); }

        var html = "";

        $_.each(pt.codes, function (index_, code) {

            if (!code || !code.id || !code.name) { return self.displayError("Invalid code at index " + index_, "populateCodeList"); }

            html += "<option value='" + code.id + "'>" + code.name + "</option>";
        });

        $_(listSelector_).html(html);
    };

问题描述:

我在我的代码中调用上面的函数如下:

app_.populateCodeList("First Attribute", self.selectors.add_attribute_dialog + " .attribute-name");

一切正常。但是,当我尝试使用第二个属性分隔调用上面的函数时 用逗号如下:

 app_.populateCodeList("First Attribute,Second Attribute", self.selectors.add_attribute_dialog + " .attribute-name");

我收到以下错误Invalid PT:First Attribute,Second Attribute in populateCodeList,这是上述代码if (!pt) { return self.displayError("Invalid PT: " + ptName_, "populateCodeList"); }中此行的结果

所以基本上我的代码没有被编程来处理用逗号分隔的两个参数,但是单行变量显示在行中

var pt = self.registry.pt[ptName_];

如何确保上述行在需要时接受单参数和双参数?

由于

2 个答案:

答案 0 :(得分:1)

您可以拆分分隔符或允许函数使用者传递数组。以下是第一个建议的示例:

this.populateCodeList = function (ptName_, listSelector_) {

    if (!ptName_) { return self.displayError("Invalid pt name", "populatecodeList"); }
    if (!listSelector_) { return self.displayError("Invalid list selector", "populatecodeList"); }

    var ptNames = ptName_.split(',');
    // if empty, nothing was passed
    if (!ptNames.length) { return self.displayError("No pt names supplied"); }
    // iterate over all matches
    var html = "";

    ptNames.forEach(function(ptName) {
       var pt = self.registry.pt[ptName];
       if (!pt) { return self.displayError("Invalid PT: " + ptName, "populateCodeList"); }

       $_.each(pt.codes, function (index_, code) {

          if (!code || !code.id || !code.name) { return self.displayError("Invalid code at index " + index_, "populateCodeList"); }

          html += "<option value='" + code.id + "'>" + code.name + "</option>";
       });

    });

    $_(listSelector_).html(html);
};

答案 1 :(得分:0)

以下是传递数组的方法。

app_.populateCodeList(["First Attribute","Second Attribute"], self.selectors.add_attribute_dialog + " .attribute-name");

并将其命名为:

this.populateCodeList = function (ptNames_, $list_) {
   ...
   $list_.html(html);
}

app_.populateCodeList(["First Attribute","Second Attribute"], 
                      $_(self.selectors.add_attribute_dialog + " .attribute-name") );

我也发现将jQuery元素传递给函数而不是选择器更好(例如:

{{1}}