Skip to content

Instantly share code, notes, and snippets.

@Caballerog
Created October 9, 2019 20:32
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Caballerog/81a5ead0479a376530010dbdf53d13ba to your computer and use it in GitHub Desktop.
/**
* @class Service
*
* Manages the data of the application.
*/
class UserService {
constructor() {
const users = JSON.parse(localStorage.getItem('users')) || [];
this.users = users.map(user => new User(user));
}
bindUserListChanged(callback) {
this.onUserListChanged = callback;
}
_commit(users) {
this.onUserListChanged(users);
localStorage.setItem('users', JSON.stringify(users));
}
add(user) {
this.users.push(new User(user));
this._commit(this.users);
}
edit(id, userToEdit) {
this.users = this.users.map(user =>
user.id === id
? new User({
...user,
...userToEdit
})
: user
);
this._commit(this.users);
}
delete(_id) {
this.users = this.users.filter(({ id }) => id !== _id);
this._commit(this.users);
}
toggle(_id) {
this.users = this.users.map(user =>
user.id === _id ? new User({ ...user, complete: !user.complete }) : user
);
this._commit(this.users);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment