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

This is an attempt to implement the idea of channel mixin. The whole idea is based on https://www.youtube.com/watch?v=W2DgDNQZOwo&index=6&list=PLb0IAmt7-GS1cbw4qonlQztYV1TAW0sCr, which allows you to send event through channel and get it at the other end.

However, I run into some problems when try sending mouse move event over a channel which causes it to misbehave and return incorrect value of the event. I work around by cloning the event before passing it around.

@ubolonton
Copy link

It's likely the event object was mutated by React.

@ubolonton
Copy link

@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