Knockout添加选项以选择列表

时间:2017-06-08 14:35:59

标签: knockout.js

我正在努力弄清楚如何动态地向选择列表中正确添加更多选项。

此代码有效,但它会清除数组中存在的所有内容,因为它设置数组的值而不是推送:

// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers(opts);
}

此代码不起作用,它只是在下拉列表选择列表中添加一个空白项:

// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers.push(opts);
}

视图模型:

var SellerOptionModel = function() {
  var self = this;
  self.sellers = ko.observableArray([]);
  self.sellerID = ko.observable();
}

完整的JS功能,上面的KO代码在成功部分:

$("#nextForm").on('click', function(e) {
  e.preventDefault();
  var room = $("#roomSelect").val();
  var invalidItems = invalidItemsArr.join(",");
  $("#invalidItems").val(invalidItems);
  if(verify == "True") {
    var seller = $('#sellerSelect').val();
  }
  if(room == "") {
    e.preventDefault();
    slideDownMsg("Please select a room first.");
    slideUpMsg(4000);
  } else {
    var firstName = capitalizeFirstLetter($.trim($("#firstName").val()));
    var lastName = capitalizeFirstLetter($.trim($("#lastName").val()));
    if(verify != "True" && (firstName == "" || lastName == "")) {
      e.preventDefault();
      slideDownMsg("Please fill in the student's first and last name.");
      slideUpMsg(3500);
    } else if(seller == "") {
      e.preventDefault();
      slideDownMsg("Please select a seller from the dropdown.");
      slideUpMsg(3500);
    } else { // all good we can save the student
      $.ajax({
        url: '@Url.Action("SaveStudent", "Tally")',
        type: 'POST',
        data: $("#tallyForm").serialize(),
        success: function (result) {
          if(result.success == true) {
            var studentName = firstName + " " + lastName;
            slideDownMsg("Tally entry saved for " + studentName + ".");
            slideUpMsg(4000);
            var room = $("#roomSelect").val();
            $("#tallyForm")[0].reset();
            $("#roomSelect").val(room);
            tallyViewModel.items([]);
            tallyViewModel.addLine();
            if(room != "") {
              getImage(room);
            }
            tallyViewModel.runningQty(0);
            tallyViewModel.runningTotal(0);

            // add seller to dropdown list
            var opts = [];
            opts.push({Text: studentName, Value: result.sellerID});
            console.log("opts: " + JSON.stringify(opts));
            if (sellerOptionModel.sellers.indexOf(opts) < 0) {
              sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID})
            }
            sellerOptionModel.sellers.sort();
          } else {
            slideDownMsg("Failed saving tally entry for " + firstName + " " + lastName + ".");
            slideUpMsg(4000);
          }
        },
        error: function (request, status, error) {
          e.preventDefault();
          displayError("Error", request.responseText);
        }
      });
    }
  }
});

1 个答案:

答案 0 :(得分:2)

将项目动态添加到knockout中的选择列表应该像将项目添加到选择列表绑定到的可观察数组一样简单。诀窍不是替换现有数组的内容。

您应该直接将项目推送到原始的可观察数组中,而不是创建新数组,并将可观察数组设置为它。

sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});

如果项目尚不存在,则仅添加项目的问题归结为您如何定义项目是否是同一项目。通常,如果“对象”是完全相同的对象引用,则它只是等效的,并且具有相同内部值的类似对象不计算在内。例如:

var a = { id: 3 };
var b = { id: 3 };
console.log(a == b); //returns false;

您真正想要用来比较选项对象的可能是您给它们的Value属性。 indexOf无法帮助您,因此您需要手动循环浏览项目并根据新项目的值检查每个项目的Value属性。

var match = false;
for (var i = 0; i < sellerOptionModel.sellers().length; i++) {
    if(sellerOptionModel.sellers()[i].Value == result.sellerID){
        match = true;
        break;
    }
}
if (!match) {
    console.log("new id added");
    sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});
    sellerOptionModel.sellers.sort();
}else{
    console.log("id already exists")
}

工作示例:https://jsfiddle.net/jlspake/8c3tvn9u/