Search code examples
javascriptjqueryasynchronousgetjsonstocks

How to create a Javascript object that keeps track of a stock price?


I would like to make a program that can keep track of multiple stock objects and display basic information about them (IE: their price).

I have this code which can successfully retrieve the price of the stock:

function getStock(symbol, callback){
          var url = 'https://query.yahooapis.com/v1/public/yql';
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function (data) {
       result = data.query.results.quote.LastTradePriceOnly;
           callback(result);
        })
        .fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log('Request failed: ' + err);
        });
}

getStock("goog", function(){alert(result)});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I would like to be able to create a simple object that can keep track of a stock. However, I have problems with asynchrony and the JSON request. Here is my code with the "stock" object:

function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

  $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function(data) {
      result = data.query.results.quote.LastTradePriceOnly;
      callback(result);
    })
    .fail(function(jqxhr, textStatus, error) {
      var err = textStatus + ", " + error;
      console.log('Request failed: ' + err);
    });
}

function stock(symbol) {

  this.price = 0;

  getStock(symbol, function(result) { //this function is my callback
    console.log(result);
    this.price = result;
  });

  this.printPrice = function() {
    alert("The price is: " + this.price);
  }
}


var s = new stock("goog");
$("#button").click(function() {
  s.printPrice()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Print Price</button>

As you may notice, I tried using a callback which seems to be the appropriate solution to this problem (new to Javascript). However, it doesn't seem to actually be setting the class variable. In the console it does print the correct price, but it doesnt seem to change "this.price" (which is what I need it to do)

Any advice as to why this doesn't work, or how to create an "updateStockPrice()" method would be really helpful.


Solution

  • The this you are calling on

    s.printPrice()
    

    is no longer in the same scope to be able to use

    alert("The price is: " + this.price);
    

    So add a reference to the initial this to further access its variable in your class:

    var that = this;
    

    function getStock(symbol, callback) {
      var url = 'https://query.yahooapis.com/v1/public/yql';
      var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
    
      $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
        .done(function(data) {
          result = data.query.results.quote.LastTradePriceOnly;
          callback(result);
        })
        .fail(function(jqxhr, textStatus, error) {
          var err = textStatus + ", " + error;
          console.log('Request failed: ' + err);
        });
    }
    
    function stock(symbol) {
    
      var that = this;
      
      that.price = 0;
    
      getStock(symbol, function(result) { //this function is my callback
        console.log(result);
        console.log("1");
        that.price = result;
      });
    
      that.printPrice = function() {
        alert("The price is: " + that.price);
      }
    }
    
    
    var s = new stock("goog");
    $("#button").click(function() {
      s.printPrice()
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="button">Print Price</button>