Search code examples
javascripthooklifecycleeditorjs

Editor.js lifecycle hooks


How do I implement the lifecyle hooks for blocks?

https://editorjs.io/tools-api#lifecycle-hooks

I have this:

let config = { 
    /** 
     * Id of Element that should contain the Editor 
     */ 
    holder : 'alinea-5', 
    
    /** 
     * Available Tools list. 
     * Pass Tool's class or Settings object for each Tool you want to use 
     */ 
    tools: {
        header  : Header,
        list        : List
    }
};

const elEditorData = document.querySelector('.js-editor-data');

if (elEditorData.value) {
    config.data         = {};
    config.data.blocks  = JSON.parse(elEditorData.value);
}

new EditorJS(config);

enter image description here

As you can see there is some editor.js stuff out there.

I need to clean up my html when removing a block. Now I have to do something with lifecycle hook "removed", but how? When deleting the block via the toolbar I want to clean up the whole html block:

document.querySelector('.alinea-5').remove();

Is this interfering with what the documentation is saying about the delete event?

removed : Called after Block contents is removed from the page but before Block instance deleted


Solution

  • Block Lifecycle Hooks are available inside blocks:

    class MyBlockTool {
       /**
       * Called after Block content is added to the page
       */
      rendered() {}
    
      /**
       * Called each time Block content is updated
       */
      updated() {}
    
      /**
       * Called after Block content is removed from the page but before Block instance deleted
       */
      removed() {}
    
      /**
       * Called after Block is moved by move tunes or through the API
       * 
       * @param {MoveEvent} event 
       */
      moved(event) {}
    }