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

Add a method to emit multiple messages in one callback #660

Merged
merged 5 commits into from
Sep 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,19 @@ where
}
}

/// This method sends batch of messages back to the component's loop
pub fn send_back_batch<F, IN>(&mut self, function: F) -> Callback<IN>
where
F: Fn(IN) -> Vec<COMP::Message> + 'static,
{
let scope = self.scope.clone();
let closure = move |input| {
let messages = function(input);
scope.clone().send_message_batch(messages);
};
closure.into()
}

/// This method sends messages back to the component's loop.
pub fn send_back<F, IN>(&mut self, function: F) -> Callback<IN>
where
Expand Down
12 changes: 11 additions & 1 deletion src/html/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub type NodeCell = Rc<RefCell<Option<Node>>>;
pub(crate) enum ComponentUpdate<COMP: Component> {
/// Wraps messages for a component.
Message(COMP::Message),
/// Wraps batch of messages for a component.
MessageBatch(Vec<COMP::Message>),
/// Wraps properties for a component.
Properties(COMP::Properties),
}
Expand Down Expand Up @@ -59,6 +61,11 @@ where
pub fn send_message(&mut self, msg: COMP::Message) {
self.update(ComponentUpdate::Message(msg));
}

/// send batch of messages to the component
pub fn send_message_batch(&mut self, messages: Vec<COMP::Message>) {
self.update(ComponentUpdate::MessageBatch(messages));
}
}

enum ComponentState<COMP: Component> {
Expand Down Expand Up @@ -249,7 +256,10 @@ where
self.shared_state.replace(match current_state {
ComponentState::Created(mut this) => {
let should_update = match self.update {
ComponentUpdate::Message(msg) => this.component.update(msg),
ComponentUpdate::Message(message) => this.component.update(message),
ComponentUpdate::MessageBatch(messages) => messages
.into_iter()
.fold(false, |acc, msg| this.component.update(msg) || acc),
ComponentUpdate::Properties(props) => this.component.change(props),
};
let next_state = if should_update { this.update() } else { this };
Expand Down