What if we wanted to use backbone-style event delegation within the component paradigm afforded by react/preact/etc? Would that be useful?
Basic usage:
class Foo extends DelegatedComponent {
events = {
'click ul': 'selectItem'
};
selectItem(e) {
console.log(e.currentTarget.textContent); // 3
}
render() {
return <ul>{ [1,2,3,4,5].map( n => <li>{n}</li> ) }</ul>
}
}
Maybe we want to have a component that provides this?
const Demo = () => (
<Delegate {{
'click li': e => console.log(e.target.textContent)
}}>
<ul>
<li>a</li>
<li>b</li>
</ul>
</Delegate>
);
render(<Demo />, document.body);
Via a higher order function:
const Demo2 = delegate({
'click li': e => console.log(e.target.textContent)
})( () => (
<ul>
<li>a</li>
<li>b</li>
</ul>
));
render(<Demo />, document.body);
... or via a decorator:
@delegate({
'click li': e => console.log(e.target.textContent)
})
class Demo {
render() {
return (
<ul>
<li>a</li>
<li>b</li>
</ul>
);
}
}
render(<Demo />, document.body);