0

我有一个现有的视图模型,其中列出了我想要转换率的货币代码。我利用 Yahoo Finance API 为我的货币获取 JSON 结果。

如何将此第 3 方 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}]}
4

1 回答 1

1

我必须承认,我不是 100% 确定您实际上在问什么,但我认为您是在执行您用作 jsonp 回调方法的 parseExchangeRate 之后?

在您的情况下,您需要深入了解该 Yahoo 返回对象以获取 name 属性(猜测为 query.results.row.name)并拆分该字符串以获得您的两种货币。

function parseExchangeRate(yahooData)
{
    var currencies = yahooData.query.results.row.name;

    // split the string to get your two currencies
    var from = whatever;
    var to = whatever;
    var rate = yahooData.query.results.row.rate;

然后,我将更改您的 AddCurrency 方法以获取数据对象

    CurrencyModel.AddCurrency(from, to, rate);
}

    self.AddCurrency = function (from, to, rate) {
        self.Currencies.push({
            CurrencyFrom: from,
            CurrencyTo: to,
            ConversionRate: rate
        });
    };

这就是你所追求的吗?

于 2013-01-17T14:16:41.587 回答