如何创建一个跟踪股票价格的Javascript对象?

时间:2015-04-14 00:48:19

标签: javascript jquery asynchronous getjson stocks

我想制作一个程序,可以跟踪多个库存对象并显示有关它们的基本信息(IE:它们的价格)。

我有这个代码可以成功检索股票的价格:

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>

我希望能够创建一个可以跟踪股票的简单对象。但是,我遇到了异步和JSON请求的问题。这是我的代码与“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);
    });
}

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>

正如您可能注意到的,我尝试使用回调,这似乎是解决此问题的适当方法(Javascript新手)。但是,它似乎并没有真正设置类变量。在控制台中它确实打印了正确的价格,但它似乎没有改变“this.price”(这是我需要它做的)

关于为什么这不起作用,或者如何创建“updateStockPrice()”方法的任何建议都会非常有用。

4 个答案:

答案 0 :(得分:1)

我为此整理了一个jQuery插件。希望这对某人有帮助

<!-- import jQuery and the plugin -->
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/jquery-stockquotes/dist/jquery.stockquotes.js"></script>
<link rel="stylesheet" type="text/css" href="bower_components/jquery-stockquotes/dist/jquery.stockquotes.css" />

<!-- the HTML integration -->
Twitter:  <span class="stock-quote" data-symbol="TWTR"></span>
Facebook: <span class="stock-quote" data-symbol="FB"></span>
Google:   <span class="stock-quote" data-symbol="GOOGL"></span>
Netflix:  <span class="stock-quote" data-symbol="NTFLX"></span>
Yahoo:    <span class="stock-quote" data-symbol="YHOO"></span>

<!-- the JS integration -->
<script>
$(document).on('ready', function () {
  $('.stock-quote').stockQuotes();
});
</script>

enter image description here

https://github.com/ajwhite/jquery-stockquotes

答案 1 :(得分:0)

你正在呼唤

s.printPrice()

不再属于同一范围,无法使用

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

因此,请添加对初始this的引用,以进一步访问其类中的变量:

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>

答案 2 :(得分:0)

我刚刚将var price更改为top,以使其声明为函数的全局。通过这种方式,他们共享它并且您可以打印它。

希望它会帮助你!!

   function getStock(symbol, callback) {
  var url = 'https://query.yahooapis.com/v1/public/yql';
  var price=0;
  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) {


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

  this.printPrice = function() {
    alert("The price is: " + 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>

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>

答案 3 :(得分:0)

现在是时候向 ES5 bind 方法打招呼来设置执行上下文了。 Stock.getStock现在返回承诺 - 点击后将执行查询股票的最新价格。

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;

    this.getStock = function () {
        var dfd = jQuery.Deferred();
        getStock(symbol, function (result) {
            this.price = result;
            dfd.resolve(result);
        }.bind(this));
        return dfd.promise();
    }.bind(this);

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

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