Skip to content
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

Support passing callbacks to elements #777

Merged
merged 2 commits into from
Dec 7, 2019

Conversation

jstarry
Copy link
Member

@jstarry jstarry commented Dec 7, 2019

Problem

The only way to specify listeners for elements is with the magical closure syntax. That approach is not very flexible and is inconsistent with the syntax so this change allows setting a callback struct as a listener.

New syntax:

use yew::{html, Callback, ClickEvent, Component, ComponentLink, Html, ShouldRender};

struct Model {
    onclick: Callback<ClickEvent>,
}

enum Msg {
    Click,
}

impl Component for Model {
    type Message = Msg;
    type Properties = ();

    fn create(_: Self::Properties, mut link: ComponentLink<Self>) -> Self {
        Model {
            onclick: link.send_back(|_| Msg::Click }
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Click => true,
        }
    }

    fn view(&self) -> Html<Self> {
        html! {
            <button onclick=self.onclick>{ "Click me!" }</button>
        }
    }
}

@hgzimmerman
Copy link
Member

hgzimmerman commented Dec 7, 2019

This feels like the right way to handle the awkwardness of using link as was discussed in #756.

Edit: specifically the creation of callbacks in create.

@jstarry jstarry merged commit c583f73 into yewstack:master Dec 7, 2019
@jstarry jstarry deleted the vtag-callback branch December 9, 2019 00:00
llebout pushed a commit to llebout/yew that referenced this pull request Jan 20, 2020
* Support passing callbacks to elements

* Fix tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants