Yew: How to get scroll position?

Created on 2 Dec 2019  路  3Comments  路  Source: yewstack/yew

i need to hide and show a custom appbar. wonder what i can do in rust.

question

Most helpful comment

Hi @thienpow, happy you were able to find a workaround! Here's an approach that should work with state (NOTE: I didn't test any of this code)

First, you'll want to create a scroll callback. This step is crucial because it links the callback to your component. Behind the scenes, Yew will make sure to call your component's update method with the Msg

fn create(_, : Self::Properties, mut link: ComponentLink<Self>) -> Self {
  // ...

  let callback = link.send_back(|_: ScrollEvent| Msg::PageScroll(window.page_y_offset()));

  // ...
}

Then, inside your closure you can call:

let callback = link.send_back(|_: ScrollEvent| Msg::PageScroll(window.page_y_offset()));
window.add_event_listener(enclose!( (window) move |e: ScrollEvent| {
  callback.emit(e);
})));

And finally, in order to get a reference to your appbar, you can use a NodeRef. Check out this example: https://github.com/yewstack/yew/tree/master/examples/node_refs

All 3 comments

i am able of getting the page_y_offset from window... but not able to update the state via Msg that trigger update function

Screenshot 2019-12-02 at 1 22 06 PM

my current workaround is to ignore dealing with state... instead go directly to document query_selector.

Screenshot 2019-12-02 at 3 15 23 PM

Hi @thienpow, happy you were able to find a workaround! Here's an approach that should work with state (NOTE: I didn't test any of this code)

First, you'll want to create a scroll callback. This step is crucial because it links the callback to your component. Behind the scenes, Yew will make sure to call your component's update method with the Msg

fn create(_, : Self::Properties, mut link: ComponentLink<Self>) -> Self {
  // ...

  let callback = link.send_back(|_: ScrollEvent| Msg::PageScroll(window.page_y_offset()));

  // ...
}

Then, inside your closure you can call:

let callback = link.send_back(|_: ScrollEvent| Msg::PageScroll(window.page_y_offset()));
window.add_event_listener(enclose!( (window) move |e: ScrollEvent| {
  callback.emit(e);
})));

And finally, in order to get a reference to your appbar, you can use a NodeRef. Check out this example: https://github.com/yewstack/yew/tree/master/examples/node_refs

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  4Comments

zethra picture zethra  路  5Comments

sackery picture sackery  路  3Comments

agausmann picture agausmann  路  3Comments

Boscop picture Boscop  路  4Comments