I have a basic table set up using knockout, but I was wondering if there is any way to edit/save a single record, rather than having to save the entire view model every time a change is made? Here’s my code…
<tbody data-bind="foreach: movies">
<tr>
<td data-bind="text: title"></td>
<td data-bind="text: releaseDate"></td>
<td data-bind="text: genre"></td>
<td data-bind="text: price"></td>
<td><input type="button" value="Edit" id="edit"/></td>
</tr>
<tr class="editable"> <!-- hide this initially, only show when edit button is clicked -->
<td><input id="titleInput" data-bind="value: title" /></td>
<td><input id="releaseDateInput" data-bind="value: releaseDate" /></td>
<td><input id="genreInput" data-bind="value: genre" /></td>
<td><input id="priceInput" data-bind="value: price" /></td>
</tr>
<!-- save button/form or something here containing ONLY this record -->
</tbody>
</table>
<script type="text/javascript">
function Film(data) {
this.title = ko.observable(data.Title);
this.releaseDate = ko.observable(data.ReleaseDate);
this.genre = ko.observable(data.Genre);
this.price = ko.observable(data.Price);
}
function MovieListViewModel() {
var self = this;
self.movies = ko.observableArray([]);
self.title = ko.observable();
self.releaseDate = ko.observable();
self.genre = ko.observable();
self.price = ko.observable();
$.getJSON("/Movies/GetAllMovies", function (allMovies) {
var mappedMovies = $.map(allMovies, function (movie) { return new Film(movie) });
self.movies(mappedMovies);
});
}
ko.applyBindings(new MovieListViewModel());
Any thoughts? Thanks!
Actually, through the magic of binding contexts, this is quite easy!
Step one. Place the following element anywhere inside your foreach template.
Step two. Add the
saveMoviemethod to your viewModelThe
movievariable will contain the item of your foreach loop! Why? Because in Knockout, we have the amazing feature called binding contexts:http://knockoutjs.com/documentation/binding-context.html