在Corona SDK中更新网络请求。

我正在使用 network.request 函数从网站获取某些 json 数据(比特币的价值)。然而,我希望每当用户按下“更新”时,json 数据(比特币价值)都能更新到最新版本。这该如何实现?

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 )

这是我使用的所有代码。

点赞
用户869951
用户869951

参考优秀的Corona buttons文档页面,你应该将你的network.request放到该页面上第一个示例的handleButtonEvent中。这样,每当用户点击按钮时,就会发出一个新的请求。一旦响应到达,btcValue函数将被调用,从而根据响应内容设置dollarbtc值。目前,你的update回调函数会在每个时间段检查响应数据是否可用。因此,至少应该在更新文本小部件后取消dollarbtc(将其设置为nil),否则你将在每个时间段更新小部件!

local function update()
    if (dollarbtc) then
        btcPriceText.text = "BTC"..dollarbtc
        dollarbtc = nil -- do come here again, text field updated!
    end
end

然而,你甚至不需要这样做:在处理响应时更新文本小部件:

local function btcValue(event)
    local btcValue = json.decode(event.response)
    local dollarbtc= btcValue[1]['rate']
    btcPriceText.text = "BTC"..dollarbtc
end

而且你可以忘记Runtime:addEventListener( "enterFrame", update )这一行,不再需要。

不要忘记添加一个display.yourButton:addEventListener("tap", handleButtonEvent),这样按钮就可以响应点击事件了。点击事件没有阶段(而触摸事件有)。

2014-01-24 18:15:19