将属性从Int转换为String,并在KnockoutJS中显示

Convert Property from Int to String and show it in KnockoutJS

本文关键字:并在 KnockoutJS 显示 String 属性 Int 转换      更新时间:2023-10-01

我想用我创建的json将Int值转换为字符串。我的变量ResultType在INT中,我想显示它的转换值。ResultType保存我的数据库中的值int,所以"1"、"2"等。

这是我的main.js代码

function InvestigatorInfo() {
  var self = this;
  self.ResultType = ko.observable();
}
InvestigatorInfo.prototype.fromJS = function(data) {
  var self = this;
  self.ResultType(data.ResultType || "");
}

我的观点:

<ul data-bind="foreach:Infos">
<b>ResultType: </b><span data-bind="text: resultName[ResultType]"></span>

这是我的转换代码:

resultName = {"0":"INVALID_VALUE","1":"NONE","2":"BOOLEAN"}

我需要在我的原型函数中首先检查int吗?任何帮助都是徒劳的。感谢

您可以使用ko.computed

在下面的示例中,我将类型/名称映射(resultTypeNames)作为静态构造函数属性。

function InvestigatorInfo() {
  var self = this;
  self.ResultType = ko.observable();
  self.ResultName = ko.computed(function () {
    return InvestigatorInfo.resultTypeNames[self.ResultType()] || "UNKNOWN";
  });
}
InvestigatorInfo.prototype.fromJS = function(data) {
  var self = this;
  self.ResultType(data.ResultType || "");
  return self;
}
InvestigatorInfo.resultTypeNames = {
  "0":"INVALID_VALUE",
  "1":"NONE",
  "2":"BOOLEAN"
}
var response = [
  { ResultType: "0" },
  { ResultType: "2" },
  { ResultType: "1" },
  { ResultType: "4" }
];
ko.applyBindings({
  Infos: ko.utils.arrayMap(response, function (data) {
    return new InvestigatorInfo().fromJS(data);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach:Infos">
  <li>
    <b>ResultType:</b>
    <span data-bind="text: ResultName"></span> (<span data-bind="text: ResultType"></span>)
  </li>
</ul>