0

I am trying to make a function wrapper, to disable my button clicks. I would like this function to be general. This is my disable function:

  disable = (event, fn) => {
    let disabled = false;
    return (...args) => {
      if (!disabled) {
        disabled = true;
        const target = event.target || event.srcElement || event.currentTarget;
        target.disabled = disabled;
        fn(...args);
      }
    };
  }

I can call the disable from my button like this:

<button (click)="disable($event, login)('hello')">Sign in</button>

The problem is that when fn() is called, this is not anymore in the scope. I know I am trying to blend some different fn and oop here. Can I somehow pass this or make it part of the scope?

I hope it's possible, for I would love to use this pattern!

Can I accomplish it without adding this as a parameter?

disable = (event, fn) => {
    let disabled = false;
    return (...args) => {
      if (!disabled) {
        disabled = true;
        const target = event.target || event.srcElement || event.currentTarget;
        target.disabled = disabled;
        fn(this, ...args);
      }
    };
  }

The above is a bad solution because the disable function isn't located in the component.

0

1 Answer 1

2

You can use fn.apply(this, ...).

Sign up to request clarification or add additional context in comments.

3 Comments

Yes I figured that out just as I wrote :)
I don't help me much though. If I refactor this to some general place I don't have a reference for this..
You have to define disable using the normal function declaration (not arrow notation). Using arrow notation, this will be always referring to the this of the scope where the function was defined. If you define it in a global scope, then this will be undefined. Using the normal function declaration, this will depend on how this function was called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.