将Property从Int转换为String并在KnockoutJS中显示

我想将我的Int值转换为我创build的json的string。 我的variablesResultType是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吗? 任何帮助将是apreciated。 谢谢

您可以使用ko.computed

在下面的示例中,我将types/名称映射( 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>