Home > Software design >  invoking only existing method
invoking only existing method

Time:01-07

I have a ref that contains a method that turns window into full screen. However, this method name changes depending the browser:

  const setFullscreen = () => {
    if (!elRef.current) return;

    elRef.current
      .requestFullscreen() // webkitRequestFullScreen on Safari
      .then(() => {

        setIsFullscreen(document[getBrowserFullScreenElementProp()] != null);
      })
      .catch(() => {
        setIsFullscreen(false);
      });
  };

As you can see, Safari uses webkitRequestFullscreen, so the above code doesn't work in Safari.

How can I make the code work keeping it DRY? Found something similar here (link) but it won't help keeping it DRY.

I was thinking in something like:

const requestFullScreen = elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen;

requestFullScreen().then .... more

However this doesn't invoke the method in neither of the browsers.

CodePudding user response:

Probably You need to bind method to the target before calling it:

const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen).bind(elRef.current);

requestFullScreen().then .... more

You can also add the failsafe with || () => {} at the end to not crash when both requestFullscreen and webkitRequestFullscreen do not exist:

const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen || () => {}).bind(elRef.current);

requestFullScreen().then .... more
  •  Tags:  
  • Related