Created
January 21, 2015 19:20
-
-
Save misuba/b4dd08bd984f992a88cd to your computer and use it in GitHub Desktop.
React bridge for Google Hangouts API - requires Immutable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Loiterer = function(toplevel, dest) { | |
this.toplevel = React.createFactory(toplevel); | |
this.dest = dest; | |
this.atom = Immutable.Map(); | |
this.messages = Immutable.List(); | |
gapi.hangout.data.onStateChanged.add(this.recvState.bind(this)); | |
gapi.hangout.data.onMessageReceived.add(this.recvMessage.bind(this)); | |
this.redraw(); | |
}; | |
Loiterer.prototype = { | |
recvState: function(data) { | |
var state = {}; | |
for (var key in data.state) { | |
state[key] = JSON.parse(data.state[key]); | |
} | |
this.atom = Immutable.fromJS(state); | |
this.redraw(); | |
}, | |
recvMessage: function(msg) { | |
this.messages = this.messages.push(Immutable.fromJS(msg)); | |
this.redraw(); | |
}, | |
sendDiff: function(path, newState) { | |
var obj = {}; | |
var newValueAtKey = newState.getIn([path[0]]); | |
if (newValueAtKey === null) { | |
gapi.hangout.data.submitDelta({}, [path[0]]); | |
} else { | |
obj[path[0]] = JSON.stringify(newValueAtKey.toJS()); | |
gapi.hangout.data.submitDelta(obj, []); | |
} | |
}, | |
valueAlreadyAtPath: function(path) { | |
return !!this.atom.getIn(path); | |
}, | |
setIn: function(path, val, tempVal) { | |
var newState = this.atom.setIn(path, val); | |
this.sendDiff(path, newState); | |
if (typeof tempVal !== undefined && this.valueAlreadyAtPath(path)) { | |
this.atom = this.atom.setIn(path, tempVal); | |
this.redraw(); | |
} | |
}, | |
redraw: function() { | |
React.render(React.createElement(this.toplevel, { | |
data: this.atom, | |
messages: this.messages, | |
setIn: this.setIn.bind(this), | |
sendMsg: function(msg) { | |
gapi.hangout.data.sendMessage(msg); | |
} | |
}, null), this.dest); | |
} | |
} | |
// var loiterer = new Loiterer(MainReactElement, document.querySelector('#main')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment