I've been struggling for too long with the following issue. I've been searching online and I haven't found an answer to my issue. I have a form which I added a with data-bind. When I call ko.applyBindings(viewModel) I don't get any errors, but the HTML inside gets removed.
What I am trying to accomplish is the following:
- I have a generated HTML that has no knockout
- I'm dynamically injecting knockout bindings to the html based on known input ids.
- I want to be able to apply bindings at the top level which will be my form instead of adding each individual binding.
Code
HTML
<form data-bind="with: form1">
<select data-bind="options: propertyNames, value: selectedProperty"></select>
<input data-bind="value: currentValue" />
<input data-bind="value: currentValue002" />
<button data-bind="click: setValue">Set Value</button>
<button data-bind="click: setValue2.bind($data, 'two', 'Jon')">Set two to Jon</button></form>
ViewModel:
<div data-bind="text: ko.toJSON($root.properties)"></div>
var viewModel = {
propertyNames: ["one", "two", "three"],
form1: ko.observable(),
properties: {
one: ko.observable("Bob"),
two: ko.observable("Ted"),
three: ko.observable("Ann")
},
setValue: function() {
this.properties[this.selectedProperty()](this.currentValue());
},
setValue2: function(propName, value) {
this.properties[propName](value);
}
};
ko.applyBindings(viewModel);
You can see it here: http://jsfiddle.net/cricri99/Hk6MB/2/
I also tried to add data-bind="submit: form1" to my form and then surround the inner HTML with a div with data-bind="with: test" and that didn't work either. It also removed the inner HTLM.
<!-- ko with: form1 --> <form></form> <!-- /ko -->But this does NOT help. I'm wondering what valueform1will have when you bind it -- Normally, you'd have something like<form data-bind="with: object"> <imput data-bind="value: objectProp1" /> </form>- Cody