react icon indicating copy to clipboard operation
react copied to clipboard

Declarative API for installing global DOM event handlers

Open sophiebits opened this issue 13 years ago • 63 comments

#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.)

sophiebits avatar Aug 21 '13 21:08 sophiebits

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.

jareware avatar Feb 11 '15 14:02 jareware

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 avatar Apr 06 '15 03:04 nelix

@nelix do events only propagate but not bubble in your proposal?

chicoxyzzy avatar Apr 06 '15 03:04 chicoxyzzy

+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.

brigand avatar Apr 06 '15 04:04 brigand

Couldn't agree more with all above poster, +1

limelights avatar Apr 23 '15 16:04 limelights

+1 to @brigand's suggestion

quantizor avatar Apr 24 '15 09:04 quantizor

:+1:

thepag avatar May 15 '15 00:05 thepag

+1

mouhsinelonly avatar May 26 '15 09:05 mouhsinelonly

+1

robink avatar Jun 17 '15 14:06 robink

+1

kexhest avatar Jun 23 '15 09:06 kexhest

+1 (Currently using mousetrap)

meghprkh avatar Jul 06 '15 16:07 meghprkh

:+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');
    }

ctrlaltdylan avatar Sep 02 '15 19:09 ctrlaltdylan

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
  }
}

blainekasten avatar Sep 02 '15 19:09 blainekasten

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.

blainekasten avatar Oct 13 '15 18:10 blainekasten

fwiw, I created an abuse of this pattern as an example: https://github.com/blainekasten/react-global-event-decorator/tree/master

blainekasten avatar Oct 14 '15 14:10 blainekasten

@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.

brigand avatar Oct 16 '15 13:10 brigand

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.

blainekasten avatar Oct 16 '15 13:10 blainekasten

:+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.

narqo avatar Jan 07 '16 17:01 narqo

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.

milesj avatar Jan 07 '16 18:01 milesj

:+1: (decorators don't feel like the right pattern for this to me though)

jkillian avatar Jan 08 '16 21:01 jkillian