Created
March 26, 2015 00:40
-
-
Save JedWatson/18eb2582f5d957053a1d to your computer and use it in GitHub Desktop.
Simple store-prototype example for a User Store + View
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 Store = require('store-prototype'); | |
var UserStore = new Store(); | |
var users = {}; | |
var loaded = false; | |
UserStore.extend({ | |
loadUsers: function() { | |
loadUsersSomehow(function(err, results) { | |
users = results; | |
this.notifyChange(); | |
}); | |
}, | |
getUsers: function() { | |
if (!loaded) this.loadUsers(); | |
return users; | |
}, | |
getUser: function(id) { | |
return users[id]; | |
}, | |
isLoaded: function() { | |
return loaded; | |
}, | |
updateUser: function(data) { | |
updateUserSomehow(data, function(err, result) { | |
users[result.id] = result; | |
this.notifyChange(); | |
}); | |
}, | |
removeUser: function(id) { | |
delete users[id]; | |
this.notifyChange(); | |
removeUserSomehow(id, function(err) { | |
// rollback on err maybe? | |
}); | |
} | |
}); | |
module.exports = UserStore; |
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 UserStore = require('UserStore'); | |
var UserView = React.createClass({ | |
getInitialState: function() { | |
return this.getUserState(); | |
}, | |
getUserState: function() { | |
return { | |
users: UserStore.getUsers(), | |
ready: UserStore.isLoaded() | |
}; | |
}, | |
updateUserState: function() { | |
this.setState(this.getUserState()); | |
}, | |
componentDidMount: function() { | |
UserStore.addChangeListener(this.updateUserState); | |
if (!this.state.ready) UserStore.loadUsers(); | |
}, | |
componentWillUnmount: function() { | |
UserStore.removeChangeListener(this.updateUserState); | |
}, | |
render: function() { | |
if (!this.ready) return <div>Loading...</div>; | |
return <UserList users={this.state.users} />; | |
} | |
}); | |
var UserList = React.createComponent({ | |
render: function() { | |
var rows = this.props.users.map(function(user) { | |
return <UserRow user={user} /> | |
}); | |
return <div>{rows}</div>; | |
} | |
}); | |
var UserRow = React.createComponent({ | |
removeUser: function() { | |
UserStore.removeUser(this.props.user.id); | |
}, | |
render: function() { | |
return ( | |
<div> | |
{this.props.user.name} | |
<button onclick={this.removeUser}>remove</button> | |
</div>; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment