I have a ViewModel which accepts JSON to build observableArray()
and also have a selected observable
for storing the object when editing.
var ViewModel = function (data) {
var self = this;
self.list = ko.observableArray(data);
self.selected = ko.observable();
}
I'm showing the list
in a table with edit button. On edit, the selected object goes into selected
self.edit = function (o) {
self.selected = ko.observable(o);
}
Next, I have a form which binds with the selected
and displays all the properties.
<form>
<input type="text" data-bind="value: selected().Name">
</form>
The problem is that I want this form to be shown for adding an item and not only when the user clicks edit. But initially, the selected observable
is undefined and throws error. Also, I want to push the data in selected
to my observableArray
when the user clicks on Add button.
What will be the best approach? Where can I put a custom binding so that this scenario works?
Update
My problem is similar this question.
But I can't implement the given solution to an observable
Fiddle implementing a part of problem and a suggested solution