如何将第三方JSON结果绑定到现有的Knockout Viewmodel

时间:2013-01-17 07:45:11

标签: json knockout.js

我有一个现有的视图模型,列出了我想要转换率的货币代码。我利用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"}}}});

我的Viewmodel代码:

    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}]}

1 个答案:

答案 0 :(得分: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
        });
    };

这就是你追求的目标吗?