Skip to content

Commit

Permalink
Add a method to emit multiple messages in one callback (yewstack#660)
Browse files Browse the repository at this point in the history
* feat: add create_effect method to help create effect callback

* style: fmt code with rustfmt

* feat: support bunch update in one render loop

* typo: change bunch to batch

* style: fmt with cargo
  • Loading branch information
stkevintan authored and llebout committed Jan 20, 2020
1 parent d47c338 commit b3a057e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
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

0 comments on commit b3a057e

Please sign in to comment.