-
-
Save jeffrydegrande/020d3b3a74520c62121f to your computer and use it in GitHub Desktop.
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
// first pattern I use | |
// People is where I put most of the logic of fetching and updating stuff | |
// PeopleComponent is top level component. Imagine a bunch of PersonComponent's | |
// below ... any component in this hierarchy can do something that ultimately | |
// triggers People.onPeopleAdded which will be picked up by the top level component | |
// which will push the update state all the way down. Idea is to force state to flow in | |
// a single direction only, starting from a single position | |
var People = { | |
onPeopleAdded: function(data) { | |
$(this).trigger('people:added', data); | |
}, | |
load: function() { | |
$.get("/people", function(data) { | |
this.onPeopleAdded(data); | |
}.bind(this)); | |
}, | |
_eoo: true | |
}; | |
var PeopleComponent = React.createClass({ | |
getInitialState: function () { | |
return { people: []}; | |
} | |
componentDidMount: function() { | |
$(People).bind('people:added', function(event, data) { | |
this.setState({people: data}); | |
}.bind(this)) | |
People.load(); | |
}, | |
componentDidUnmount: function() { | |
$(People).unbind('people:added'); | |
}, | |
render: function() { | |
return ( | |
<div className="People"></div> | |
); | |
}, | |
_eoo: true | |
}); | |
// 2nd pattern I use. Parent component passes it's own functions down | |
// to child component as a prop which when executed gets executed in the | |
// context of the parent, giving access to this.setState and friends | |
var PeopleComponent = React.createClass({ | |
render: function() { | |
var people = this.state.people.map(function(person) { | |
return <PersonComponent person={person} onClick={this.personWasClicked.bind(this)} />; | |
}); | |
return ( | |
<div className="PeopleComponent">{people}</div> | |
); | |
}, | |
personWasClicked: function(person) { | |
// now can do something with person in relation to this.state | |
}, | |
_eoo: true | |
}); | |
var PersonComponent = React.createClass({ | |
render: function() { | |
// should be passed implicitly but this is what it does. | |
return <div onClick={this.props.onClick}></div> | |
}, | |
_eoo: true | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment