【问题标题】:How to create a Javascript object that keeps track of a stock price?如何创建一个跟踪股票价格的 Javascript 对象?
【发布时间】:2015-06-19 11:25:43
【问题描述】:

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

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

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 请求的问题。这是我的带有“股票”对象的代码:

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()”方法的任何建议都会非常有帮助。

【问题讨论】:

标签: javascript jquery asynchronous getjson stocks


【解决方案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>

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

【讨论】:

    【解决方案2】:

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

    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>

    【讨论】:

      【解决方案3】:

      我只是将 var price 更改为顶部,使其声明为全局函数。这样,他们都可以共享它,您就可以打印它。

      希望对你有帮助!!

         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>

      【讨论】:

        【解决方案4】:

        你正在调用的这个

        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>

        【讨论】:

        • 请解释您的答案,而不是简单地发布修改后的代码。这可以让其他用户知道您所做/更改的内容并提供学习机会。
        • 我认为他对“那个”和范围的初始解释很有帮助。感谢您的回答!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-26
        • 2020-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多