Run code when an element is shown?


#1

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


#2

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.


#3

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.


#4

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


#5

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();
    }
  }
}

#6

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.


#7

Agreed. Thank you much for this.