Run code when an element is shown?

Is there a built in way to run code when an element with an if.bind is shown or destroyed? Something like init.delegate="".

Normally I would implement a …Changed(newValue, oldValue) method for the property being evaluated in the if.bind, but the case I have is more complicated, I can’t put code on the object being checked.

Not sure if I’m approaching this the right way or not…

Thanks-

Erik

If your if binding on the outside of a custom element it should be firing the attached() and detached() methods within that element’s view model when it is attached to the dom and removed from it.

If you are if binding to an element that isn’t a custom element and can’t be a custom element you could create a custom attribute that can give you callbacks for attached() and detached() using something like the @dynamicOptions decorator to allow you to bind those callbacks.

1 Like

A custom attribute is a great idea! I’ll explore now. Thanks for the suggestion.

For a simple reusable custom attribute, you can try this to hook up attached callback.
detached would almost be a copy-paste.

<button if.bind="condition" 
        attached.call="btnAttached()">My button</button>
export class AttachedCustomAttribute {
  attached() {
    if (typeof this.value === 'function') {
      this.value();
    }
  }
}

Comparing to @Malexion’s suggestion using @dynamicOptions (which definitely works), I feel separating attached and detached custom attributes is easier to understand, and easier to use.

Agreed. Thank you much for this.