Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some MVVM class based approach thing
// Imagine this is a starting page where the user creates their account
function CreateUserViewModel()
{
// could be done via IoC to improve testability and reuseability
var someAjaxService = {}; // Imagine it does something
this.user = new User();
var saveDataToServer = function() {
var data = ko.toJS(this.user);
someAjaxService.Post("/users", data);
}
this.createUser = function() {
if(this.user.isValid()) {
saveDataToServer();
}
}
}
function User() {
this.id = ko.observable(0);
this.name = ko.observable("default").extend({required: true, minLength: 10, maxLength: 30);
this.email = ko.observable("not valid").extend({required: true, email: true });
}
// Assume this view model is on a page and the user is viewing their account
function ViewUserViewModel()
{
var someAjaxService = {}; // Imagine it does something
this.user = new User();
var updateUserData = function(userData) {
ko.merge(this.user, userData);
}
this.populateUserFromServer = function(userId) {
someAjaxService.Get("/users", userId)
.then(updateUserData);
};
}
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.