0

我正忙于为我的 Web 应用程序创建货币模块,我正在使用 Yahoo Finance API 返回我在本地数据库中定义的 2 种货币的货币兑换率。我从 API 获得了很好的 JSON 数据,我只想使用 ko.computed 将从 Finance API 收到的 JSON 数据绑定到我现有的 Viewmodel。我不确定我是否应该使用 ko.computed 来实现这一点,所以任何建议都会有很大帮助。

这是我的代码:

    var currency = function (data) {
        var self = this;
        self.CurrencyFrom = ko.observable(data.CurrencyFrom);
        self.CurrencyTo = ko.observable(data.CurrencyTo);
        self.ConversionRate = ko.computed(rates); // I WANT TO BIND THE VALUE FROM API HERE
    }

    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) {
           getRate(item.CurrencyFrom, item.CurrencyTo);

           return new currency(item);
       }
       );
                self.Currencies(MappedCurrencies);

            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });
    };

    //3rd Party JSON result from Yahoo Finance API
    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=rates"); //HERE I CALL THE VALUE TO OBTAIN THE CONVERSION RATE FROM API
        document.body.appendChild(script);
    }


    //I WANT TO ADD THIS TO MY VIEWMODEL
    var rates = function parseExchangeRate(YahooData) {
                var rate = YahooData.query.results.row.rate;
        }


    $(document).ready(function () {
        var VM = new CurrencyModel();
        ko.applyBindings(VM);
        $('[rel=tooltip]').tooltip();
    })

从 parseExchangeRate 函数返回的 JSON(雅虎查询结果):

parseExchangeRate({"query":{"count":1,"created":"2013-01-18T06:46:41Z","lang":"en-US","results":{"row":{"rate":"0.1129","name":"ZAR to USD"}}}});
4

1 回答 1

1

我看到您已经在使用 jquery,所以我也会将 jquery 用于 JSONP。我使用了一个简单的 ko.observable 作为转换率,并添加了一个“裸”的 ko.computed 来执行 ajax 请求并异步更新 observable。如果您需要任何进一步的说明,请告诉我。

JSFiddle 示例(使用模拟数据而不是初始 ajax):http: //jsfiddle.net/VsW5H/1/

更新代码:

var currency = function (data) {
  var self = this;
  self.CurrencyFrom = ko.observable(data.CurrencyFrom);
  self.CurrencyTo = ko.observable(data.CurrencyTo);
  self.ConversionRate = ko.observable(data.ConversionRate);

  ko.computed(function () {
    var from = self.CurrencyFrom(),
      to = self.CurrencyTo();

    if (!from || !to) {
      self.ConversionRate("N/A");
      return;
    }

    getRate(from, to).done(function (YahooData) {
      console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
      self.ConversionRate(YahooData.query.results.row.rate);
    });
  });
}

var CurrencyModel = function (Currencies) {
  var self = this;
  self.Currencies = ko.observableArray(Currencies);

  self.AddCurrency = function () {
    self.Currencies.push(new currency({
      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 from Yahoo Finance API
function getRate(from, to) {
  return $.getJSON("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=?");
}
于 2013-01-19T15:46:47.350 回答