Reputation: 2617
I am trying to dynamically create observables but its not quite working. Here is what I have:
//this type works
this.Name = ko.observable(data.Name);
this.Age = ko.observable(data.Age);
//This is what I want to work
for (var propertyName in data) {
this.propertyName = ko.observable(propertyName);
}
This produces just the property name i.e "Name", and "Age" but the first one produces the value and name when I debug like "Name" is "John".
Upvotes: 1
Views: 71
Reputation: 15053
What about:
for (var propertyName in data) {
this[propertyName] = ko.observable(data[propertyName]);
}
this.propertyName will actually set a property named "propertyName". By using brackets, you can use variables to define a property.
ko.observable(propertyName); was defining an observable with the property name as its value.
You might also want to check if the value is an array so you can create an observable array where needed:
for (var propertyName in data) {
var value = data[propertyName];
if ($.isArray(value)) { // assuming your using jQuery
this[propertyName] = ko.observableArray(value);
} else {
this[propertyName] = ko.observable(value);
}
}
Upvotes: 5