Click here to Skip to main content
15,897,334 members

Bind 3rd Party JSON data to Existing Viewmodel

dr_fu asked:

Open original thread
I am busy creating a currency Module for my web app, I am using Yahoo Finance API to return the currency conversion rate of 2 currencies that I have defined in my local DB. I get the JSON data fine from the API, I just want to Bind the JSON data that I have received from the Finance API to my existing Viewmodel so that I can use it.

Here is my code:

JavaScript
var currency = function (data) {
           var self = this;
           self.CurrencyFrom = ko.observable(data.CurrencyFrom);
           self.CurrencyTo = ko.observable(data.CurrencyTo);
           self.ConversionRate = ko.observable(); // I WANT TO BIND MY RATE THAT IS RETURNED FROM YAHOO FINANCE API (parseExchangeRate Function) 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=parseExchangeRate");
           document.body.appendChild(script);
       }

        //THIS IS THE PRIMARY FUNCTION TO GET RATE FROM JSON
       function parseExchangeRate(YahooData) {
           var rate = YahooData.query.results.row.rate;
           //I WANT TO BIND THIS RATE TO MY VIEW MODEL
       }

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

My JSON Data Returned from my App:
{"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}]}

The JSON returned from parseExchangeRate Function (Yahoo Query Result):
parseExchangeRate({"query":{"count":1,"created":"2013-01-18T06:46:41Z","lang":"en-US","results":{"row":{"rate":"0.1129","name":"ZAR to USD"}}}});
Tags: Ajax, jQuery, Knockout.js, JSON

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900