Declarative API for installing global DOM event handlers
#284 reminded me that one thing I've sometimes wanted is to install a handler on window for keypress (for keyboard shortcuts) or scroll. Right now I can just do window.addEventListener in componentDidMount but since React is listening already, it would be nice if there were some way for me to intercept those events. (In addition, receiving normalized synthetic events is generally more useful.)
I'm looking for a solution like this as well! As in, having a standard DOM event called, say, MyWeirdEvent and being somehow able to tell React to start managing it exactly as it does events like click, with e.g.
<SomeComponent onMyWeirdEvent={handler} />
Currently the React event system feels quite exclusive of any 3rd party libs.
I think https://github.com/facebook/react/issues/285#issuecomment-65231515 is a pretty good idea, but its kind of messy. I normally connect window/document level events to flux or pass it down the app tree. It would be nice if you could pass an option to React.render to define it as the app entry point, and delegate those events to it.
class App extends React.Document {
handleResize() { this.forceUpdate() }
render() { return <div onDocumentResize={this.handleResize.bind(this)}/>; }
}
React.render(<App/>, document.body, {delegateEvents: true});
Kind of off topic, but this could be related to work making react handle being mounted on document.body function more sensibly... If it were safer to mount react on the document body you could delegate body events by default.
@nelix do events only propagate but not bubble in your proposal?
+1 to React.{add,remove}EventListener. Provide the minimum api to hook into react's event system, and let third party libs build on this as they see fit.
Couldn't agree more with all above poster, +1
+1 to @brigand's suggestion
:+1:
+1
+1
+1
+1 (Currently using mousetrap)
:+1: But I'm really digging keymaster
componentDidMount: function() {
key('esc', this.onClose)
},
componentWillUnmount: function() {
key.unbind('esc', this.onClose)
},
onClose: function() {
console.log('awoiejf');
}
It'd be super rad to use ES7 decorators in a declaritive way like so:
class Component {
@globalEvent('click')
onGlobalClick(e) {
// handle window click
}
render() {
// render
}
}
Decorator Comment Edit:
This wouldn't actually be a logical approach to using decorators as they would just be mounted as functions on the class prototype. Not executed automatically when mounted. The only way this could be implemented (without giving it much thought) would be for the @globalEvent decorator to register the method name with a predictable signature that could be searchable.
Something like:
@globalEvent('click')
onGlobalClick(e) { ... }
// compiled
_reactGlobalEvent{UUID}: handler
Then there would have to be some sort of mechanism internally that searches for similar keys:
/*
* @internal
*/
function bindGlobalHandlers(component) {
for (var method in component ) {
if (method.indexOf('_reactGlobalEvent') === 0) {
React.bindGlobalMethod(method);
}
}
}
Here is a potential implementation approach to the decorator:
function globalEvent(eventType) {
return function decorate(target, key, descriptor) {
function reactGlobalBind() {
React.globalEvent(eventType, descriptor.value)
}
Object.defineProperty(
target,
'_reactGlobalEvent' + Date.now(), // not a good UUID
{ value: reactGlobalBind }
);
}
}
class Component extends React.Component {
@globalEvent('click')
onGlobalClick(e) {
console.log('clicked');
}
}
Full discretion
This is basically an abuse of the decorator pattern But it does make a nice implementation detail. Though it doesn't appeal to those who can't utilize the decorator pattern.
fwiw, I created an abuse of this pattern as an example: https://github.com/blainekasten/react-global-event-decorator/tree/master
@blainekasten different take on the same thing: https://github.com/brigand/react-global-event-method
I don't really like either of them though, specifically for the componentDidMount/etc issue. Maybe annotating the functions with the method decorators and still using a class decorator would be the way to go?
It'd still be cool to have this in core, mostly so we get the same event shimming benefits normal react events give.
The componentDidMount issue could be solved if this was an internal react implementation. But again, I'm not selling this as the way to go. Just a thought and experiment.
:+1: here.
API like onDocument<EventName> and onWindow<EventName> would be very handy. As well as imperative React.addEventListener(element, <EventName>, ...).
There are millions of articles currently which suggest to use simple <node>.addEventListener() in the componentDidMount hook in case one needs it, but no one clarifies that such things should be done through event delegation. At least helpers like React.addEventListener could prevent redundant memory consumption in most of react plugins out the box.
Why not make use of the current JSX on event handlers and extend them? Anything that should be bound to the window, or the document, or global, should simply be prefixed, like so?
class Foo extends React.Component {
render() {
return (
<input
onKeyDown={this.onKeyDown} // Element event
onWindowKeyDown={this.onWindowKeyDown} // Window event
onDocumentSelectionChange={this.onDocumentSelectionChange} // Document event
onGlobalMouseWheel={this.onGlobalMouseWheel} // Global event
/>
);
}
}
This approach does not require lifecycle events, decorators, new syntax, new external APIs, is easy to use and understand, is clean and straightforward, etc. It's akin to appending Capture to existing events.
Personally, it would be a better idea to improve React's internal event system, by providing new event types, instead of moving this logic to the component layer.
:+1: (decorators don't feel like the right pattern for this to me though)