Does anyone know if it is possible to generate the viewmodel for knockoutjs automatically.
1) I have (for example) the following html code:
<input type="text" data-bind="value: XYZ" />
<input type="text" data-bind="value: ABC" />
<input type="text" data-bind="value: Prop1" />
2) Then I need to create a viewmodel like this:
function ViewModel()
{
this.XYZ = ko.observable();
this.ABC = ko.observable();
this.Prop1 = ko.observable();
}
I would like to skip step 2, because I already defined the properties which should be available in the html-markup (sort of).
update: As mentioned in the comments, there would be drawbacks to do such a thing. (That's probably the reason it is not supported by knockoutjs). I will take a different approach, but nevertheless I made a simple Javascript function which can generate a ViewModel out of a VERY simple markup. If anyone is interested, that's what I came up with:
function getViewModelFromView(selector) {
var vm = {};
$("[data-bind]", selector).each(function () {
var attribute = $(this).attr("data-bind");
if (attribute.indexOf(':') > 0) {
vm[attribute.slice(attribute.indexOf(':')+1).trim()] = ko.observable();
}
});
return vm;
}