From 39aeb66ffff43144f908fef4e871728337677266 Mon Sep 17 00:00:00 2001 From: "Denis V. Dedkov" Date: Sat, 11 Aug 2018 08:01:31 +0200 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D1=82=D0=B0=D1=89=D0=B8=D0=BB=20ht?= =?UTF-8?q?tp-=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD=D1=82=20=D0=B2=20=D0=BE=D1=82?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HttpClient.qml | 30 ++++++++++++++++++++++++++++++ LightsModel.qml | 37 +++++++++++++++---------------------- qml.qrc | 1 + 3 files changed, 46 insertions(+), 22 deletions(-) create mode 100644 HttpClient.qml diff --git a/HttpClient.qml b/HttpClient.qml new file mode 100644 index 0000000..802b605 --- /dev/null +++ b/HttpClient.qml @@ -0,0 +1,30 @@ +import QtQuick 2.0 + +QtObject { + id: root + + signal reply(var data) + signal error(string text) + + function get(url) { + var request = new XMLHttpRequest() + + request.open('GET', url) + request.onreadystatechange = function () { + if (request.readyState !== XMLHttpRequest.DONE) { + return + } + + if (request.status === 200) { + root.reply(JSON.parse(request.responseText)) + return + } + + root.error(qsTr("[%1] Request error: %2"). + arg(request.status). + arg(request.statusText)) + } + + request.send() + } +} diff --git a/LightsModel.qml b/LightsModel.qml index e2d4140..4e8b1c6 100644 --- a/LightsModel.qml +++ b/LightsModel.qml @@ -3,6 +3,20 @@ import QtQml.Models 2.1 ListModel { id: root + readonly property var httpClient: HttpClient { + id: httpClient + + onError: { + root.error(text) + root.isLoading = false + } + + onReply: { + root.populateModel(data) + root.isLoading = false + } + } + property string serviceUrl: undefined property bool isLoading: false @@ -11,29 +25,8 @@ ListModel { onServiceUrlChanged: reload() function reload() { - var request = new XMLHttpRequest() - - request.open('GET', root.serviceUrl + '/static/channels.js') - request.onreadystatechange = function () { - if (request.readyState !== XMLHttpRequest.DONE) { - return - } - - if (request.status === 200) { - populateModel(JSON.parse(request.responseText)) - root.isLoading = false - return - } - - root.error(qsTr("[%1] Request error: %2"). - arg(request.status). - arg(request.statusText)) - - root.isLoading = false - } - + root.httpClient.get(root.serviceUrl + '/static/channels.js') root.isLoading = true - request.send() } function populateModel(data) { diff --git a/qml.qrc b/qml.qrc index eae51c0..5c3e215 100644 --- a/qml.qrc +++ b/qml.qrc @@ -11,5 +11,6 @@ GradientButton.qml lamp.png Off.png + HttpClient.qml