Implementing change for callbacks
Question
I am implementing a button of a third party JS framework (onsen).
Anyway a button always receives a callback for the onclick event.
Now when I try to implement fn change(&mut self, props: Self::Properties) -> ShouldRender {
my problem is how can I check a callback for equality, can I just ignore it?
For visual rendering it shouldn't be required but if somebody adds just a different callback I should just assign the callback in change and be good?
This is something that I have found to be an issue in some situations since the callbacks are added as event listeners on each render - if you open the devtools and check the number of event listeners it steadily increases until GC cleans things up, then the cycle repeats.
I believe this TODO is relevant here and would ease some of the difficulty here:
https://github.com/yewstack/yew/blob/master/src/virtual_dom/vtag.rs#L453
@mdtusz we should have an issue for that but I think it's a different issue. The code you linked to is for vtag which manages html element listeners. @krampenschiesser is asking about component callbacks.
I think we can solve this by putting an id in the callback. As long as you don't create callbacks in view(), you will be passing in callbacks that can be matched by their id.
@krampenschiesser would you like to take a stab at this? You'll need to:
- Add an ID to Callback
- Generate a new ID for each new Callback (could use a static callback counter)
- Implement PartialEq for Callback
Sorry, didn't answer your question...
For visual rendering it shouldn't be required but if somebody adds just a different callback I should just assign the callback in change and be good?
This depends. If you use the passed in callback in your view method like this:
fn view(&self) -> Html {
let onmouseover = self.props.on_hover.reform(|_| Hovered::Header);
html! {
<div class="list-header" onmouseover=onmouseover>
{ &self.props.text }
</div>
}
}
You would need to re-render in order to not call the wrong callback.
If you only call the passed in callback in update, then you wouldn't need to re-render, and you could just assign the callback and be good as you said 👍
@jstarry I started working on this issue and immediately noticed that Callback is already implementing PatialEq and using Rc::ptr_eq to compare a set of callbacks. I would expect this to already be sufficient to distinguish between different callbacks and don't fully understand how adding an ID to Callback could help here.
I'm just getting started looking into Yew so perhaps I'm missing out on something, and I was hoping you could clear this out for me.
@joaquindk oh! I assumed it wasn't implemented because of the issue. I agree that the current implementation should be sufficient.
The other issue that @mdtusz brought up is here: https://github.com/yewstack/yew/issues/943
Thanks for your response @jstarry. I’ll give #943 a go then ☺️