I'm creating an observable array from JSON that comes from the server.
var ViewModel = function (data) {
var self = this;
self.list = ko.observableArray(data);
self.selected = ko.observable();
}
I'm able to bind the properties with my UI
<form data-bind="with: selected">
<input type="text" data-bind="value: Name">
<button type="submit" class="btn btn-primary" data-bind="click: $root.create">Save</button>
</form>
I also have an edit method on click which puts the selected object into selected
self.edit = function (o) {
self.selected(o);
}
Code for iterating through the list:
<tbody data-bind="foreach: list">
<tr>
<td data-bind="text: Name"></td>
<td><button data-bind="click: $root.edit">edit</button></td>
</tr>
</tbody>
The code for creating is as follows:
self.create = function (formElement) {
$(formElement).validate();
if ($(formElement).valid()) {
$.post(baseUri, $(formElement).serialize(), null, "json")
.done(function (o) {
self.list.push(o);
});
}
}
So how can I use the same form for adding an object? I'm a little confused with the data-bind on the form. I can't show the form without selecting an object.
From all the examples I have seen, it seems I have to create a ViewModel with the properties hard coded. I don't want to do that since I have many views with many properties. What can be the best approach to this?
Update
This is exactly what I need : CRUD but with a ViewModel that gets generated from JSON and I don't have to manually create it.