Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In react.js is there any way to disable all children events

I want to build an application which has two states; pause and active. For example I want to disable all children/owned components' events like onClick, onChange, onKeyDown, .etc.

I had thought to give isActive=false prop through all it's children/owned components and check for the property isActive on event handlers. If isActive property is falsy event handler will do nothing. I can make this mechanism even easier with a simple helper function. But my concern is when I changed the app state to paused, all children components needs to be re-rendered.

Im searching for a way to bypass all event handlers (not custom ones) without re render all components.

UPDATE: I watch rendering rectangles on chrome end it doesn't re render the children. But if there any better reacty way to do this I want to learn it.

like image 765
Umur Gedik Avatar asked Sep 05 '25 03:09

Umur Gedik


1 Answers

One way to solve this is using a simple guard abstraction. It works like this:

var sayHi = guard("enabled", function(){
  alert("hi");
});

guard.deactivate("enabled");
sayHi(); // nothing happens
guard.activate("enabled");
sayHi(); // shows the alert

Using this for event handlers is similar:

handleChange: guard("something", function(e){
  // if 'something' is deactivated, the input won't change
  this.setState({value: e.target.value});
})

// or

return <div onClick={guard("something", this.handleClick)}>click me!</div>

Here's an implementation of guard

var guard = function(key, fn){
  return function(){
    if (guard.flags[key]) {
      return fn.apply(this, arguments);    
    } 
  };
};

guard.flags = {};
guard.activate = function(key){ guard.flags[key] = true };
guard.deactivate = function(key){ guard.flags[key] = false };
like image 174
Brigand Avatar answered Sep 07 '25 22:09

Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!