Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Gists related to my "Knockout JS mappings" blogpost at http://marcofranssen.nl
function CompanyViewModel (data) {
var companyMapping = {
'ignore': ['address', 'website'],
'name': {
'create': function (options) {
return ko.observable(options.data.toUpperCase());
}
},
'employees': {
key: 'peronsId',
create: function (options) {
return new PersonViewModel(options.data);
}
}
};
ko.mapping.fromJS(data, companyMapping, this);
}
var mapping = {
'ignore': ['twitter', 'webpage'],
'copy': ['age', 'personId'],
'lastName': {
'create': function (options) {
return ko.observable(options.data.toUpperCase());
}
}
};
viewModel = ko.mapping.fromJS(data, mapping);
var viewModel;
// result could look like this: "{ "personId": 1, "firstName": "Marco", "lastName": "Franssen", "age": 26, "webpage": "http://marcofranssen.nl", "twitter": "@marcofranssen" }"$.ajax({
url: 'http://somewebpage.net/getPerson'
type: 'GET',
dataType: 'JSON',
success: function (result) {
var data = JSON.parse(result);
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel, $('#person').get(0));
},
error: function (result) {
//handle the error, left for brevity
}
});
viewModel = {
personId: data.personId,
firstName: ko.observable(data.firstNametoUpperCase()),
lastName: ko.observable(data.lastName),
age: data.age,
};
var viewModel = {
persons: ko.observableArray(),
};
var persons = JSON.parse(jsonPersonArray);
for (person in persons) {
viewModel.persons.push(person);
}
//Or even better performance wise (persons observableArray gets updated only once)
viewModel.persons.push.apply(viewModel.persons, persons);
function PersonViewModel(data) {
var personMapping = {
'ignore': ['twitter', 'webpage'],
'copy': ['age'],
'lastName': {
'create': function (options) {
return ko.observable(options.data.toUpperCase());
}
}
};
ko.mapping.fromJS(data, personMapping, this);
this.fullName = ko.computed(function () {
return this.firstName() + ' ' + this.lastName();
}, this);
}
var comany;
$.ajax({
url: 'http://companyindex.org/getcompanydata/4327/',
type: 'GET',
dataType: 'JSON',
success: function (result) {
var data = JSON.parse(result);
company = new CompanyViewModel(data);
ko.applyBindings(company, $('#company').get(0));
},
error: function (result) {
//left for brevity
}
});
var data = JSON.parse(result);
viewModel = {
personId: ko.observable(data.firstName),
firstName: ko.observable(data.firstName),
lastName: ko.observable(data.lastName),
age: ko.observable(data.age),
webpage: ko.observable(data.webpage),
twitter: ko.observable(data.twitter)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.