简体   繁体   中英

Javascript decorator listener

I'm messing around with decorators for a bit, having an Angular background i'm trying to wrap my head around the HostListener decorator.

This is how far i got:

class Demo {
        counter = 0;

        @Listen("mousemove") onMouseMove(e?) {
            console.log(this);

            this.counter++;
        }
    }

    export function Listen(name) {
        return (target, key, descriptor) => {

            window.addEventListener(name, oldValue.bind(target));


            return descriptor;
        };
    }

    new Demo();

This is more or less the implementation only problem is passing the target/this reference as target is not initialised.

Solved, i'm using Vue so this might not be everyones answer, basically what i'm doing is calling the function just once in Vue you can add a mixin and inside this mixin the beforeMount hook will be called, thus allowing me here to call it once.

Decorator updated code:

export function Listen(name) {
    return function (target, key, descriptor) {
        if (!target.subscriptions) target.subscriptions = [];


        add(target, "Listen", key);

        if (process.client) {
            const oldValue = descriptor.value;

            descriptor.value = function() {
                target.subscriptions.push(
                    target.$eventManager.add(window, name, oldValue.bind(this))
                );
            };

            return descriptor;
        }

        return descriptor;
    };
}

const add = (target, name, functionName) => {
    if(!target.decorators) target.decorators = {};
    if(!target.decorators[name]) target.decorators[name] = [];

    target.decorators[name].push(functionName);
};

Vue mixin:

Vue.mixin({
    beforeMount: function() {
        if(this.decorators && this.decorators.Listen) {
            this.decorators.Listen.forEach(key => this[key]());
        }
    },
    destroyed: function () {
        this.$subscriptionManager.remove(this.subscriptions);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM