[英]Update a network request in Corona SDK
I am fetching some json stuff(value of bitcoin) from a website with the network.request-function. 我正在使用network.request-function从网站上获取一些json东西(比特币的价值)。 However, I want that json stuff(value of bitcoin) to update to the latest version every time the user presses update.
但是,我希望每次用户按下update时,该json东西(比特币的值)都更新为最新版本。 How would that be possible?
那怎么可能呢?
local json = require("json")
btcPriceText = display.newText("price", 50,100, "Arial", 25)
local function btcValue(event)
btcValue = json.decode(event.response)
dollarbtc= btcValue[1]['rate']
end
local function update()
if(dollarbtc) then
btcPriceText.text = "BTC"..dollarbtc
end
end
network.request( "https://bitpay.com/api/rates", "GET", btcValue )
Runtime:addEventListener( "enterFrame", update )
This is all the code I'm using. 这就是我正在使用的所有代码。
Referring to the excellent Corona docs on buttons page, you would put your network.request
in the handleButtonEvent
of the first example on that page. 参考按钮页面上出色的Corona文档 ,您可以将
network.request
放在该页面上第一个示例的handleButtonEvent
中。 This way, every time the user clicks button, a new request is made. 这样,每次用户单击按钮时,都会发出一个新请求。 As soon as response arrives, the
btcValue
function will get called, thus setting the dollarbtc
value based on the content of the response. 响应到达后,将
btcValue
调用btcValue
函数,从而根据响应的内容设置dollarbtc
值。 Currently your update
callback checks at every time frame whether the response data is available. 当前,您的
update
回调会在每个时间范围内检查响应数据是否可用。 So at very least, you should unset dollarbtc (set it to nil) after you update the text widget, otherwise you will be updating the widget at every time frame! 因此,至少在更新文本小部件之后,您应该取消设置dollarbtc(将其设置为nil),否则,您将在每个时间段都更新小部件!
local function update()
if (dollarbtc) then
btcPriceText.text = "BTC"..dollarbtc
dollarbtc = nil -- do come here again, text field updated!
end
end
However, you don't even need to do that: update the text field when handling the response: 但是,您甚至不需要这样做:在处理响应时更新文本字段:
local function btcValue(event)
local btcValue = json.decode(event.response)
local dollarbtc= btcValue[1]['rate']
btcPriceText.text = "BTC"..dollarbtc
end
and you can forget about the Runtime:addEventListener( "enterFrame", update )
line, no longer needed. 并且您可以忘记不再需要的
Runtime:addEventListener( "enterFrame", update )
行。
Don't forget to add a display.yourButton:addEventListener( "tap", handleButtonEvent)
so the button responds to clicks . 不要忘记添加
display.yourButton:addEventListener( "tap", handleButtonEvent)
以便按钮响应单击 。 The tap event does not have phases (whereas the touch event does). 点击事件没有阶段(而触摸事件有阶段)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.