Created
March 7, 2014 04:36
-
-
Save simenbrekken/9405316 to your computer and use it in GitHub Desktop.
React fetchData()
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
/** @jsx React.DOM */ | |
'use strict'; | |
var React = require('react'), | |
Router = require('./Router'), | |
Store = require('./Store'), | |
Head = require('./Head') | |
module.exports = React.createClass({ | |
displayName: 'Application', | |
getInitialState: function() { | |
return { | |
match: Router.match(this.props.path || window.location.pathname), | |
data: this.props.data | |
} | |
}, | |
getHandler: function() { | |
return this.state.match.handler | |
}, | |
setPath: function(path, callback) { | |
this.setState({ | |
match: Router.match(path) | |
}) | |
this.type.loadData(path, function(err, data) { | |
if (err) return console.error(err) | |
this.setState({ data: data }, callback) | |
}.bind(this)) | |
}, | |
componentDidMount: function() { | |
window.addEventListener('popstate', this.handlePopstate) | |
}, | |
navigate: function(path) { | |
window.history.pushState(null, null, path) | |
this.setPath(path) | |
}, | |
handleClick: function(e) { | |
if (e.target.tagName === 'A') { | |
e.preventDefault() | |
this.navigate(e.target.pathname) | |
} | |
}, | |
handlePopstate: function() { | |
var path = window.location.pathname | |
if (this.state.match.path !== path) { | |
this.setPath(path) | |
} | |
}, | |
render: function() { | |
var handler = this.getHandler(), | |
data = this.state.data | |
var metadata = data && data.metadata, | |
title = metadata && metadata.title, | |
description = metadata && metadata.description | |
return ( | |
<html> | |
<Head title={title} description={description} /> | |
<body onClick={this.handleClick}> | |
<handler params={this.state.match.params} data={data} /> | |
</body> | |
</html> | |
) | |
}, | |
statics: { | |
loadData: function (path, callback) { | |
var match = Router.match(path), | |
handler = match.handler | |
if (!handler.fetchData) return callback() | |
var store = new Store() | |
store.fetchManifest(handler.fetchData(match.params), function(err, data) { | |
if (err) return callback(err) | |
if (handler.getMetadata) data.metadata = handler.getMetadata(data) | |
callback(null, data) | |
}) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment