I'm working on an angular codebase that very frequently uses constructs like:

<c-whatever [action]='doSomething.bind(this)'>

to pass reference to the doSomething() method on the parent component to the child component. The bind() seems to be necessary, because Angular presumably stores the function object somewhere and doesn't call it by getting it from the parent component.

This irks me because it's boilerplatey, and also because it makes WebStorm throw a bunch of red squiggles because typechecking in templates isn't quite bug-free yet.

(Arguably some of those should be replaced with @Output events, but that's neither here nor there, and not all of those can.)

Since Typescript only supports stage 2 decorators, I can't use the @bound decorator in the stage 3 proposal documentation, so I tried rolling my own TS-compatible one:

function bound<T extends Function>(target: any, key: string|symbol, pd: TypedPropertyDescriptor<T>) {
    const value = pd.value;
    delete pd.value;
    delete pd.writable;
    pd.get = function() {
        console.log('get()', {'this':this});
        return value && value.bind(this);

Is there anything that sticks out here? Is it okay to delete value and writeable on the passed in descriptor or would it be better to return a new descriptor object?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.