Decorating Lifecycle Hooks in vue.js

Viewed 64

Does anyone know a good way to decorate lifecycle hooks from within the vue component? I am adding a function in the mounted in my component that gets called from the app.vue when the screen size changes. When I navigate away from the page I want to remove this function. Currently I have to do it in the destroy method on the component. If I was able to pass in the destroyed method on the component when I am creating the listener and decorate it with the logic to destroy the listener I would not have to worry about someone adding the listener on a component and not adding the removal of the listener in the destroy method.

public AddUpdateIsMobileFunction(fn: (screenType: any) => void, destroyHook: any): any {
        this.updateIsMobileFunctions.push(fn);
        const currentFunctionPlacementInArray: number = this.updateIsMobileFunctions.length;
        const destroySelf: () => void = () => {
            this.updateIsMobileFunctions.splice(currentFunctionPlacementInArray, 1);
        }
        const originalDestroyHook: any = _.deepClone(destroyHook)
        destroyHook = () => {
            originalDestroyHook();
            destroySelf();
        }
        return destroySelf;
    }

In the component

private mounted(): void {
        this.destroyIsMobileFunction = this.$Global.AddUpdateIsMobileFunction((screenType: any) => {
            this.isMobile = screenType.isMobile;
            console.log("test is mobile fn")
        }, pass in the destroyed function here )
    }
remove the function below
    private beforeDestroy(): void {
        console.log('in the destroy function in the vue component')
        this.destroyIsMobileFunction();
    }

0 Answers
Related