Skip to content

Instantly share code, notes, and snippets.

@hung-phan
Last active August 29, 2015 14:19
Show Gist options
  • Save hung-phan/10f2acb7386e26d55b10 to your computer and use it in GitHub Desktop.
Save hung-phan/10f2acb7386e26d55b10 to your computer and use it in GitHub Desktop.
Channel mixin for js-csp and react
'use strict';
import SyntheticEvent from 'react/lib/SyntheticEvent';
import {chan, putAsync} from 'js-csp';
const ChannelMixin = {
channels: {},
getEventChannel(channelName, ...args) {
return this.channels[channelName] || (this.channels[channelName] = chan(...args));
},
send(channelName, ...args) {
if (this[channelName] !== undefined && typeof(this[channelName]) === 'function') {
return this[channelName].bind(this, ...args);
} else {
let ch = this.getEventChannel(channelName, ...args);
return (eventArgs) => {
if (eventArgs instanceof SyntheticEvent && typeof(eventArgs.persist) === 'function') {
eventArgs.persist();
}
putAsync(ch, eventArgs);
};
}
}
};
export default ChannelMixin;
import React from 'react/addons';
import reactMixin from 'react-mixin';
import {go, CLOSED} from 'js-csp';
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
go(function*() {
let ch = this.getEventChannel('mouseMove');
let value;
while((value = yield ch) !== CLOSED) {
console.log(value.clientX, value.clientY);
}
}.bind(this));
}
render() {
return (
<div onMouseMove={this.send('mouseMove')} style={{width: '100%', height: '100%'}}></div>
);
}
}
reactMixin(MyComponent.prototype, ChannelMixin);
export default window.MyComponent = MyComponent;
import React from 'react/addons';
import reactMixin from 'react-mixin';
import {go, CLOSED} from 'js-csp';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.moveMove = (value) => {
console.log(value.clientX, value.clientY);
};
}
render() {
return (
<div onMouseMove={this.send('mouseMove')} style={{width: '100%', height: '100%'}}></div>
);
}
}
reactMixin(MyComponent.prototype, ChannelMixin);
export default window.MyComponent = MyComponent;
@hung-phan
Copy link
Author

Thanks @ubolonton

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment