0

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;
}
Preli
  • 2,953
  • 10
  • 37
  • 50
  • You can using mapping to observe a javascript object, but not the other way around. – Joe Nov 09 '12 at 17:53
  • 2
    Even if you could do this (you probably can, with some tricks), it will severely limit you. The point of the viewmodel is more than just to provide the structure of the data, it also provides the *functionality* of the page. With a viewmodel generated from the HTML, you will have a very difficult time making functions that accurately refer to properties. It is also not going to be possible by looking at the markup to infer complex object types, another large limitation. This whole thing is also very counter to the MVVM pattern: the viewmodel should not depend on, or even know about, the view. – Kyeotic Nov 09 '12 at 17:57
  • I only would like to generate the "simple" properties out of my markup. I know it's not the prefered way but it would be very convenient in my case. You are right, the viewmodel shoudn't know the view. I wish for a function which would create a viewmodel out of the view (the markup). Neither the view nor the viewmodel should depend on this function. I will try to create this sort of function myself if it doesn't exist. – Preli Nov 09 '12 at 18:05
  • Take a look at this answer: http://stackoverflow.com/questions/12125143/giving-initial-value-to-observable-from-the-html-markup/12135780#12135780 . You do need to put the property name in a string in the binding (`value: 'ABC'` vs. `value: ABC`) – RP Niemeyer Nov 09 '12 at 18:34

0 Answers0