JavaScript Patterns - Prototypes
Knockout and JavaScript Patterns -
by johnpapa
JavaScript
(function (win) {
"use strict";
win.my = win.my || {};
var my = win.my,
ko = win.ko; //, $ = win.$;
my.PersonVm = function pvm() {
// Private data/functions accessible only within this closure
var lastSavedStateJson = ko.observable(),
model = ko.observable(),
registerCurrentStateAsClean = function () {
//function registerCurrentStateAsClean() {
if (model()) {
lastSavedStateJson(ko.toJSON(model));
}
};
// Public functions
pvm.prototype.addFriend = function () {
this.model().Friends.push(my.ModelFactory.createFriend("sample friend"));
};
pvm.prototype.remove = function (myfriend) {
ko.utils.arrayRemoveItem(this.model().Friends, myfriend);
};
pvm.prototype.load = function () {
my.PersonDataService.getPersons(
function (result) {
// maps the result into a json object
// result = {...}
// FirstName: "John"
// LastName: "Papa"
// Friends: [[object Object],[object Object]]
model(ko.mapping.fromJS(result)); // loads the data fresh
registerCurrentStateAsClean();
});
};
pvm.prototype.save = function () {
// turns it into a json string (not a json object)
// person = "{"FirstName":"John","LastName":"Papa",
// "Friends":[
// {"IsOnTwitter":true,"Name":"Dan","TwitterName":"@danwahlin"},
// {"IsOnTwitter":false,"Name":"Landon","TwitterName":null}
// ]}"
var person = ko.mapping.toJSON(this.model());
my.PersonDataService.savePerson(
person, function (result) {
win.alert(result.message);
registerCurrentStateAsClean();
...