The beforeUpdate
function schedules work to happen immediately before the DOM has been updated. afterUpdate
is its counterpart, used for running code once the DOM is in sync with your data.
Together, they're useful for doing things imperatively that are difficult to achieve in a purely state-driven way, like updating the scroll position of an element.
This Eliza chatbot is annoying to use, because you have to keep scrolling the chat window. Let's fix that.
let div;
let autoscroll;
beforeUpdate(() => {
autoscroll = div && (div.offsetHeight + div.scrollTop) > (div.scrollHeight - 20);
});
afterUpdate(() => {
if (autoscroll) div.scrollTo(0, div.scrollHeight);
});
Note that beforeUpdate
will first run before the component has mounted, so we need to check for the existence of div
before reading its properties.
App.svelte
xxxxxxxxxx
108
1
<script>
2
import Eliza from 'elizabot';
3
import { beforeUpdate, afterUpdate } from 'svelte';
4
5
let div;
6
7
beforeUpdate(() => {
8
// determine whether we should auto-scroll
9
// once the DOM is updated...
10
});
11
12
afterUpdate(() => {
13
// ...the DOM is now in sync with the data
14
});
15
16
const eliza = new Eliza();
17
18
let comments = [
19
{ author: 'eliza', text: eliza.getInitial() }
Console
bundling https://unpkg.com/elizabot@0.0.3/elizadata.js
xxxxxxxxxx
221
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
binding_callbacks,
7
destroy_each,
8
detach,
9
element,
10
init,
11
insert,
12
listen,
13
noop,
14
null_to_empty,
15
safe_not_equal,
16
set_data,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
.chat.svelte-1qz8d72.svelte-1qz8d72{display:flex;flex-direction:column;height:100%;max-width:320px}.scrollable.svelte-1qz8d72.svelte-1qz8d72{flex:1 1 auto;border-top:1px solid #eee;margin:0 0 0.5em 0;overflow-y:auto}article.svelte-1qz8d72.svelte-1qz8d72{margin:0.5em 0}.user.svelte-1qz8d72.svelte-1qz8d72{text-align:right}span.svelte-1qz8d72.svelte-1qz8d72{padding:0.5em 1em;display:inline-block}.eliza.svelte-1qz8d72 span.svelte-1qz8d72{background-color:#eee;border-radius:1em 1em 1em 0}.user.svelte-1qz8d72 span.svelte-1qz8d72{background-color:#0074D9;color:white;border-radius:1em 1em 0 1em;word-break:break-all}