2015-04-14 4 views
0

Я хотел бы сделать программу, которая может отслеживать несколько объектов запаса и отображать основную информацию о них (IE: их цена).Как создать объект Javascript, который отслеживает цену акции?

У меня есть этот код, который может успешно восстановить цену акции:

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()» был бы очень полезен.

+1

'this' внутри вашей функции обратного вызова больше не относится к' 'this' из функции stock'. См. Http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback. – Jasen

ответ

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>

+0

Пожалуйста, объясните свой ответ, а не просто разместите пересмотренный код. Это позволяет другим пользователям узнать, что вы сделали/изменили, и предлагает возможность обучения. – matcartmill

+1

Его объяснение по инициативе с «этим» и областью действия было полезным, я думаю. Спасибо за ответ! –

0

Я просто изменил цену уага на вершину, чтобы она объявлена ​​глобальной для функций. Таким образом, все они разделяют его, и вы сможете распечатать его.

Надеюсь, что это поможет вам!

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>

0

Пора поздороваться ES5 и связывают метод установки контекста выполнения. Stock.getStock теперь возвращает обещание - после щелчка ther будет выполнен запрос по последней цене на акции.

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>

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

Смежные вопросы