0
0
Svelteframework~10 mins

Why actions add reusable element behavior in Svelte - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply an action to an element in Svelte.

Svelte
<div use:[1]></div>
Drag options to blanks, or click blank then click option'
Aclass
BonClick
Cbind
DmyAction
Attempts:
3 left
💡 Hint
Common Mistakes
Using event handlers like 'onClick' instead of an action name.
Trying to bind or add a class instead of using an action.
2fill in blank
medium

Complete the action function to receive the element it is applied to.

Svelte
function myAction([1]) {
  // action code here
}
Drag options to blanks, or click blank then click option'
Anode
Bevent
Celement
Dtarget
Attempts:
3 left
💡 Hint
Common Mistakes
Using event or target which are not the element itself.
Using a name that does not represent the element.
3fill in blank
hard

Fix the error in the action return to properly clean up when the element is removed.

Svelte
function myAction(node) {
  const handle = () => console.log('clicked');
  node.addEventListener('click', handle);
  return [1];
}
Drag options to blanks, or click blank then click option'
Anode.removeEventListener('click', handle)
B{ cleanup: () => node.removeEventListener('click', handle) }
C{ destroy: () => node.removeEventListener('click', handle) }
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Returning null or nothing, causing memory leaks.
Using a wrong method name like 'cleanup'.
4fill in blank
hard

Fill both blanks to update the action when parameters change and clean up properly.

Svelte
function myAction(node, [1]) {
  function update(params) {
    console.log(params);
  }
  update([2]);
  return {
    update,
    destroy() {
      // cleanup code
    }
  };
}
Drag options to blanks, or click blank then click option'
Aparams
BinitialParams
Coptions
Dsettings
Attempts:
3 left
💡 Hint
Common Mistakes
Not naming the second argument as parameters.
Not calling update with initial parameters.
5fill in blank
hard

Fill all three blanks to create a reusable action that adds a CSS class and removes it on destroy.

Svelte
function addClass(node, [1]) {
  node.classList.add([2]);
  return {
    destroy() {
      node.classList.[3]([2]);
    }
  };
}
Drag options to blanks, or click blank then click option'
AclassName
B'highlight'
Cremove
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add' instead of 'remove' in the destroy method.
Not passing the class name as a parameter.