-
-
Save junwatu/071f25e452178f94154e to your computer and use it in GitHub Desktop.
This file contains 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 React = require("react"), Dom = React.DOM; | |
var LogOutButton = require('./src/logout'); | |
var events = require('api/events'); | |
var Main = React.createClass({ | |
// this mixin provides this.emitLogout, and if we set onLogout it'll be called when "logout" is emitted | |
mixins: [events.mixinFor("logout")], | |
getInitialState: function(){ | |
return { | |
user: null | |
}; | |
}, | |
logIn: function(){ | |
this.setState({ | |
user: {name: "foobar"} | |
}); | |
}, | |
// update our state when the login event is emitted | |
onLogout: function(){ | |
this.setState({ | |
user: null | |
}); | |
}, | |
render: function() { | |
var user = this.state.user; | |
return Dom.div(null, | |
user && Dom.span(null, "Hi " + user.name), | |
user && LogOutButton(), | |
!user && Dom.button({onClick: this.logIn}, | |
"log in") | |
); | |
} | |
}); | |
React.renderComponent(Main(), document.body); |
This file contains 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 React = require("react"), Dom = React.DOM; | |
var events = require('api/events'); | |
var Logout = React.createClass({ | |
mixins: [events.mixinFor("logout")], | |
render: function() { | |
window.x = this | |
// directly bind our event to a button click event | |
return Dom.button({ | |
onClick: this.emitLogout | |
}, 'log out'); | |
} | |
}); | |
module.exports = Logout; |
This file contains 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 EventEmitter = require('events').EventEmitter; | |
var globalEmitter = module.exports = new EventEmitter(); | |
module.exports.mixinFor = function (eventName, events) { | |
events = events || globalEmitter; | |
// "fooBar" => "FooBar" | |
var pascal = eventName[0].toUpperCase() | |
+ eventName.slice(1); | |
var noop = function(){}; | |
var mixin = { | |
componentWillMount: function(){ | |
if (!this["on" + pascal]) { | |
return; | |
} | |
events.on(event, this["on" + pascal]); | |
}, | |
componentWillUnmount: function(){ | |
if (!this["on" + pascal]) { | |
return; | |
} | |
events.off(event, this["on" + pascal]); | |
} | |
}; | |
// add emit method | |
mixin["emit" + pascal] = | |
events.emit.bind(events, event); | |
return mixin; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment