Skip to content

Instantly share code, notes, and snippets.

@walfie
Created February 6, 2018 04:52
Show Gist options
  • Save walfie/43015edbc86df36a23621c7b1344e3ec to your computer and use it in GitHub Desktop.
Save walfie/43015edbc86df36a23621c7b1344e3ec to your computer and use it in GitHub Desktop.
yew - Trigger message on HashChangeEvent
// Valid as of yew commit a6c87e48b42e4977b008ce31281242e2b8684f9f and stdweb 0.3.0
extern crate stdweb;
#[macro_use]
extern crate yew;
use yew::prelude::*;
type Context = ();
struct Model {
hash: String,
}
enum Msg {
HashChange(String),
}
impl Component<Context> for Model {
type Msg = Msg;
type Properties = ();
fn create(context: &mut Env<Context, Self>) -> Self {
use stdweb::web::IEventTarget;
use stdweb::web::event::HashChangeEvent;
use stdweb::web::window;
let on_hash_change = context.send_back(|s: String| Msg::HashChange(s));
window().add_event_listener(move |_: HashChangeEvent| {
for location in window().location() {
on_hash_change.emit(location.hash())
}
});
Model {
hash: window()
.location()
.map_or_else(|| "".to_owned(), |l| l.hash()),
}
}
// Some details omitted. Explore the examples to get more.
fn update(&mut self, msg: Self::Msg, _: &mut Env<Context, Self>) -> ShouldRender {
match msg {
Msg::HashChange(mut new_hash) => {
::std::mem::swap(&mut self.hash, &mut new_hash);
true
}
}
}
}
impl Renderable<Context, Model> for Model {
fn view(&self) -> Html<Context, Self> {
html! {
<div>{&self.hash}</div>
<ul>
<li><a href="#/home",>{ "Home" }</a></li>
<li><a href="#/next",>{ "Next" }</a></li>
</ul>
}
}
}
fn main() {
yew::initialize();
let app: App<_, Model> = App::new(());
app.mount_to_body();
yew::run_loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment