神刀安全网

delegate-to – DOM Event delegate, it works great in React, too

delegate-to

DOM Event delegate, it works great in React, too

:white_check_mark: Clever API

:white_check_mark: Zero dependence

:white_check_mark: Server-side rendering compatible

Compare with other candidate

zenorocha/delegate is a popular library for delegate event:

delegate(document.body, '.btn', 'click', function(e) {   console.log(e.delegateTarget) }, false)

Works in React.js

render () {   <div>     <div ref="foo" />   </div> }  componentDidMount() {   delegate(this.refs.foo, '.btn', 'click', this.handleClick, false) }

Switch to delegate-to

document.body.addEventListener('click', delegate('.btn', e => {   console.log(e.delegateTarget) }), false)

Then in React.js

render () {   <div>     <div onClick={delegate('.btn', this.handelClick)} />   </div> }

You can see the advantage in delegate-to

  • Fewer API interface (only 2 arguments)

  • Works with normal addEventListener

  • React(.jsx) friendly

  • Flexibly, custom match condition

Installation

$ npm i --save delegate-to

Examples

import delegate from 'delegate-to'  render () {   <div>     <div onClick={delegate('.btn', this.handelClick)} />   </div> }  // custom match condition render () {   <div>     <div onClick={delegate(target => target.classList.contains('btn'), this.handelClick)} />   </div> }

API

delegate([selector || condition func], [dispatchEvent])

Browsers Supported

delegate-to use native el.matchs DOM API to match CSS selector , it works on IE 9+ and All morden browsers, you can try custom match condition function if you need to work with old browsers.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » delegate-to – DOM Event delegate, it works great in React, too

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址