Chron's avatar
Level 7

Expose an empty function to overrride

Can I do something like this so I pass an empty function so I can override it from other places?

// useComposable.js

export default function useComposable() {
	const doSomethingFunction = () => {}
	
	const anotherFunction = async() => {
		await doSomethingFunction();
		console.log('do another thing after...')
	}

	return { doSomethingFunction }
}
// Parent
const { doSomethingFunction } = useComposable();

doSomethingFunction = () => {
	console.log('overriden function, do something');
}
0 likes
1 reply
krisi_gjika's avatar

you can use a closure, you just need any way to set a param from outside the class; most common a setter method

class Action {
  protected \Closure $callback;
  public function __construct() {
    $this->callback = fn () => null; // default callback
  }

  public function setCallback(callback $callback) {
    $this->callback = $callback;
  }

  public function doThing() {
    return $this->callback();
  }
}

$action = new Action();
$action->doThing(); // null
$action->setCallback(fn () => true);
$action->doThing(); // true

Please or to participate in this conversation.