換算レートが必要な通貨コードをリストする既存のビュー モデルがあります。Yahoo Finance API を利用して、通貨の JSON 結果を取得します。
このサードパーティの JSON 結果を既存の ViewModel にバインドするにはどうすればよいですか。
Yahoo Finance API からの JSON:
parseExchangeRate({"query":{"count":1,"created":"2013-01-17T07:37:18Z","lang":"en-US","results":{"row":{"rate":"8.7967","name":"USD to ZAR"}}}});
私のビューモデルコード:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(getRate(data.CurrencyFrom, data.CurrencyTo));
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedCurrencies =
$.map(Result.d,
function (item) { return new currency(item); });
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result
function getRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=parseExchangeRate");
document.body.appendChild(script);
}
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
私のHTML:
<table class="table table-striped">
<thead>
<tr>
<th>
Date Updated
</th>
<th>
Currency From
</th>
<th>
Currency To
</th>
<th>
Conversion Rate
</th>
<th />
</tr>
</thead>
<tbody data-bind="foreach: Currencies">
<tr>
<td>
<label class="label">Date</label>
</td>
<td>
<input data-bind="value: CurrencyFrom, uniqueName: true" />
</td>
<td>
<input data-bind="value: CurrencyTo, uniqueName: true" />
</td>
<td>
<input data-bind="value: ConversionRate, uniqueName: true" />
</td>
<td>
<a href='#' data-bind='click: $root.RemoveCurrency'>Delete</a>
</td>
</tr>
</tbody>
</table>
私のJSONリターン:
{"d":[{"__type":"Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM","CurrencyFrom":"ZAR","CurrencyTo":"USD","Rate":null},{"__type":"Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM","CurrencyFrom":"USD","CurrencyTo":"ZAR","Rate":null}]}