litlit-html

Access parts within AsyncDirective after setValue call


Is there any way for an AsyncDirective to access its rendered parts after a setValue call?

My directive's update method calls super.update which triggers the render method, but I need a method that's called after the setValue method call has been processed, because update is not called for that.


Solution

  • Are you able to hold a reference to the part within the directive class?

    class MyDirective extends AsyncDirective {
      currentPart: Part;
    
      update(part, args) {
        this.currentPart = part;
        return this.render(...args);
      }
    
      render(promise) {
        promise.then((value) => {
          this.setValue(value);
          // do something with `this.currentPart` ?
        });
        return 'pending';
      }
      
    }
    

    Alternatively maybe you can add a MutationObserver to the element with the part instead so you can detect whatever change setValue has caused.