Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple store-prototype example for a User Store + View
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;
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
You can’t perform that action at this time.