Skip to content

Instantly share code, notes, and snippets.

@Herve07h22
Forked from jouana/BindingHook.js
Created April 12, 2021 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Herve07h22/70b5a1e57dcbd346b52082f85d4a105e to your computer and use it in GitHub Desktop.
Save Herve07h22/70b5a1e57dcbd346b52082f85d4a105e to your computer and use it in GitHub Desktop.
React MVVM example
class FriendViewModel {
_personalId;
_friend;
constructor(personalId, friend) {
this._personalId = personalId;
this._friend = friend;
}
delete() {
personalService.removePresonalFriend(this.personalId, this._friend)
}
get name () {
return this._friends.name;
}
}
export default ({ id }) => {
const viewModel = new PersonalViewModel(id);
useEffect(() => {
viewModel.onLoad();
});
return (<div>
<h1>
{
Binding({
dataContext: viewModel,
path: "fullName",
mode: ViewModelMode.OneWay
})
}
</h1>
<input value={Binding({dataContext: viewModel, path: "age", mode: ViewModelMode.TwoWay})}
<table>
{
viewModel.friends.Map(tableFriendLineBuilder)
}
</table>
</div>);
}
function tableFriendLineBuilder(friendViewModel) {
return (<tr>
<td>{Binding({dataContext: viewModel, path: "name", mode: ViewModelMode.OneWay})}</td>
<td><button onclick={friendViewModel.delete}></td>
<tr>);
}
class PersonalViewModel {
_id;
_data;
_friends;
constructor(id) {
this._id = id
}
onLoad() {
this._data = personalService.find(this.id);
this._friends = this._data.friends.map(friend => new FriendViewModel(friend));
}
get fullName () { return this._data && `${this._data.firstName} ${this._data.lastName}`; }
get age () {
return this._data.age;
}
set age (value) {
this._data.age = value;
this.raisePropertyChanged("age");
this.raisePropertyChanged("isMajor");
}
get isMajor() {
return this._data.age > 17;
}
get friends () {
return this._friends;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment