New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Creating VNode from web_sys types #1942
Comments
I think you can use Then to add callbacks for Yew components in the following manner: use yew::{prelude::*, web_sys::HtmlElement};
use wasm_bindgen::{prelude::*, JsCast};
pub struct Comp {
link: ComponentLink<Self>,
onclick_closure: Option<Closure<dyn Fn(MouseEvent)>>,
}
pub enum Msg {
Clicked(MouseEvent),
}
impl Component for Comp {
type Message = Msg;
type Properties = ();
fn create(_: yew::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
onclick_closure: None,
}
}
// fn change omitted for brevity
fn update(&mut self, msg: Self::Message) -> ShouldRender {
yew::web_sys::console::_log_1(&"CLICKED!".into());
// do something with msg here!
false
}
fn view(&self) -> Html {
let div = yew::utils::document()
.get_element_by_id(YOUR_ELEMENT_ID)
.unwrap();
Html::VRef(div.into())
}
fn rendered(&mut self, first_render: bool) {
if !first_render {
return;
}
let element: HtmlElement = yew::utils::document()
.get_element_by_id(YOUR_ELEMENT_ID)
.unwrap()
.unchecked_into();
let local_cb = self.link.callback(|e: MouseEvent| Msg::Clicked(e));
let onclick_closure = Closure::wrap(Box::new(move |e| {
local_cb.emit(e);
}) as Box<dyn Fn(MouseEvent)>);
element.set_onclick(onclick_closure.as_ref().dyn_ref());
// If the element and the onclick listener will last the duration of the app,
// then you could just call onclick_closure.forget() instead of storing it
self.onclick_closure = Some(onclick_closure);
}
} The above assumes you have some element in the DOM that you can get by it's Hopefully this resolves the problem for you, or at least helps get you going :) |
Thanks for investing time in this. For converting Markdown to HTML, So if I understand correctly the proposed solution, instead of converting everything to Anyway, I think I understand how to solve this better now. Please tell if you have more insights, otherwise I'll close the issue. |
A better solution would be to convert HTML |
The use case I have for is aimed at post-processing of HTML returned from
pulldown_cmark
, for example addingyew
callbacks for links.I ended up with the hack
[1]
below.However I didn't find an existing implemention inside
yew
for this. Maybe I didn't search deep enough, or maybe I can fix it up and contribute? Using aFrom
impl?[1]
The text was updated successfully, but these errors were encountered: