2016-03-31 8 views
1

私が作成したjsonでInt値を文字列に変換したいと思います。 私の変数ResultTypeはINTにあり、変換された値を表示したい。 ResultTypeはintの値を保持するので、 "1"、 "2"などはmy dbから取得します。ここでIntからStringにプロパティを変換してKnockoutJSで表示

は私の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ですか? 助けが得られるはずです。 ありがとう

答えて

1

ko.computedを使用できます。

以下のサンプルでは、​​タイプ/ネームマップ(​​3210)を静的コンストラクタプロパティとして配置しました。

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>

+0

http://knockoutjs.com(どちらか[公式マッピング・プラグイン]に見て、あなたがあなた自身の '.fromJS()'メソッドを実装しているので、完全 – Muli

+0

@Muliを働いた、ありがとう/documentation/plugins-mapping.html)またはhttp://coderenaissance.github.io/knockout.viewmodel/。 – Tomalak

関連する問題