Reputation: 10476
I'm using knockout js loading a list of jobs from an async service. Each job has a very long list of fields and I'm wondering if it's considered bad practice to store the data as raw json?
function Job(data) {
var self = this;
this.data = data; // is this bad practice?
this.companyName = data.CompanyName; // should I instead list out all the fields?
this.jobTitle = data.JobTitle;
// .. 50 more fields
}
function JobsViewModel() {
function getJobs() {
$.getJSON(myUrl, { myParams }, function(data) {
var mappedJobs = $.map(JSON.parse(data.value), function(item) { return new Job(item) });
self.jobs(mappedJobs);
});
}
// initial data load
getJobs();
}
... // then in my data-bindings
<label data-binding="text: data.CompanyName"></label>
versus
<label data-binding="text: companyName"></label>
The latter is cleaner and more clear, but since I have many fields, I wanted to get some opinions.
Thanks.
Upvotes: 2
Views: 1317
Reputation: 13730
You should look at the knockout mapping plugin. It will generate the properties from your data so you dont have to hand write all of the properties.
http://knockoutjs.com/documentation/plugins-mapping.html
The current approach you are using wont update the label when a property changes in the model because your properties are not observable. Using the mapping plugin will fix this as well.
Upvotes: 3