Refactor dashboard example
Reducing levels of nesting
@@ -15,16 +15,6 @@ pub enum Format {
Toml,
}
-pub struct Model {
- fetch_service: FetchService,
- ws_service: WebSocketService,
- link: ComponentLink<Model>,
- fetching: bool,
- data: Option<u32>,
- ft: Option<FetchTask>,
- ws: Option<WebSocketTask>,
-}
-
pub enum WsAction {
Connect,
SendData(AsBinary),
@@ -65,28 +55,30 @@ pub struct WsResponse {
value: u32,
}
-impl Component for Model {
- type Message = Msg;
- type Properties = ();
+pub struct Model {
+ fetch_service: FetchService,
+ ws_service: WebSocketService,
+ link: ComponentLink<Model>,
+ fetching: bool,
+ data: Option<u32>,
+ ft: Option<FetchTask>,
+ ws: Option<WebSocketTask>,
+}
- fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
- Model {
- fetch_service: FetchService::new(),
- ws_service: WebSocketService::new(),
- link,
- fetching: false,
- data: None,
- ft: None,
- ws: None,
+impl Model {
+ fn view_data(&self) -> Html {
+ if let Some(value) = self.data {
+ html! {
+ <p>{ value }</p>
+ }
+ } else {
+ html! {
+ <p>{ "Data hasn't fetched yet." }</p>
+ }
}
}
- fn update(&mut self, msg: Self::Message) -> ShouldRender {
- match msg {
- Msg::FetchData(format, binary) => {
- self.fetching = true;
- let task = match format {
- Format::Json => {
+ fn fetch_json(&mut self, binary: AsBinary) -> yew::services::fetch::FetchTask {
let callback = self.link.callback(
move |response: Response<Json<Result<DataFromFile, Error>>>| {
let (meta, Json(data)) = response.into_parts();
@@ -105,7 +97,8 @@ impl Component for Model {
self.fetch_service.fetch(request, callback)
}
}
- Format::Toml => {
+
+ pub fn fetch_toml(&mut self, binary: AsBinary) -> yew::services::fetch::FetchTask {
let callback = self.link.callback(
move |response: Response<Toml<Result<DataFromFile, Error>>>| {
let (meta, Toml(data)) = response.into_parts();
@@ -124,6 +117,31 @@ impl Component for Model {
self.fetch_service.fetch(request, callback)
}
}
+}
+
+impl Component for Model {
+ type Message = Msg;
+ type Properties = ();
+
+ fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
+ Model {
+ fetch_service: FetchService::new(),
+ ws_service: WebSocketService::new(),
+ link,
+ fetching: false,
+ data: None,
+ ft: None,
+ ws: None,
+ }
+ }
+
+ fn update(&mut self, msg: Self::Message) -> ShouldRender {
+ match msg {
+ Msg::FetchData(format, binary) => {
+ self.fetching = true;
+ let task = match format {
+ Format::Json => self.fetch_json(binary),
+ Format::Toml => self.fetch_toml(binary),
};
self.ft = Some(task);
}
@@ -204,17 +222,3 @@ impl Component for Model {
}
}
}
-
-impl Model {
- fn view_data(&self) -> Html {
- if let Some(value) = self.data {
- html! {
- <p>{ value }</p>
- }
- } else {
- html! {
- <p>{ "Data hasn't fetched yet." }</p>
- }
- }
- }
-}
