[Kagura] Kagura + Rust でWebページを作成
```rust extern crate kagura; extern crate wasm_bindgen;
use kagura::prelude::; use wasm_bindgen::prelude::;
pub fn main() { kagura::run(Component::new(init, update, render).with(Props), "app"); }
type HelloKagura = Component
struct Props;
struct State;
struct Msg;
struct Sub;
fn init(_this: &mut HelloKagura, _state: Option
fn update(_: &mut State, _: Msg) -> Cmd
fn render(_: &State) -> Html { Html::h1( Attributes::new(), Events::new(), vec![ Html::text("hello kagura"), ], ) } ```
rust
kagura::Component::new(init, update, render)
init
, update
and render
is function :
rust
init : fn() -> State
rust
update : fn(&mut State, Msg) -> Cmd<Msg, Sub>
rust
render : fn(&State) -> Html<Msg>
rust
kagura::run(component, id_of_entry_point_in_html)
rust
kagura::Html::html_tag(attributes, events, children)
attributes
: instance of kagura::Attributes
events
: instance of kagura::Events
children
: Vec<Html>
```Html
```
is made by
```rust use kagura::Html; use kagura::Attributes; use kagura::Events;
Html::ul( Attributes::new() .class("list") .class("example") .id("my-list") .string("data-fizz", "bazz"), Events::new(), vec![ Html::li(Attributes::new(), Events::new(), vec![Html::unsafetext("foo")]), Html::li(Attributes::new(), Events::new(), vec![Html::unsafetext("bar")]), Html::li(Attributes::new(), Events::new(), vec![Html::unsafe_text("baz")]) ] ) ```
rust
kagura::Html::component(component)
component
: instance of kagura::Component
update
can send message to parent compoent as Some(message).
component.subscribe(impl: Sub -> Box<Any>)
can receive message from child component and bind to own message.
```rust fn render() -> Html { Html::component( childcomponent::new().with(props).subscribe(|sub| match sub { childcomponent::Sub::Foo => Msg::Bar }) ) }
mod child_component {
fn new() -> Component
.
.
.
} ```
Cmd::none()
Cmd::none()
means nothing to do. If you return Cmd::none(), kagura will render.
Cmd::sub(sub: Sub)
If you send sub-message to parent component, use this.
Cmd::task(task: impl FnOnce(Resolver<Msg>) + 'static)
You can use this feature like callback function in JavaScript. like this:
rust
fn update(state: &mut State, msg: Msg) -> kagura::Cmd<Msg, Sub> {
use kagura::Cmd;
match msg {
Msg::ChangeMessage(message) => {
state.message = message;
Cmd::none()
}
Msg::ChangeMessageTask(message) => Cmd::task(|resolver| {
let resolver = Closure::once(|| resolver(Msg::ChangeMessage(message)));
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(
resolver.as_ref().unchecked_ref(),
1000,
);
resolver.forget();
}),
}
}
You can set a batch process to component like this:
rust
fn init(this: &mut MyComponent, _state: Option<State>, props: Props) -> (State, Cmd<Msg, Sub>) {
this.batch(batch::time::tick(1000, || Msg::SomeMsg));
.
.
.
}