如何使用挖空保存单个记录

How to save a single record with knockout

本文关键字:单个 记录 保存 何使用      更新时间:2023-09-26

我有一个使用挖空设置的基本表,但我想知道是否有任何方法可以编辑/保存单个记录,而不必在每次进行更改时都保存整个视图模型?这是我的代码...

<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());

有什么想法吗?谢谢!

实际上,通过绑定上下文的魔力,这很容易!

  1. 第一步。将以下元素放置在 foreach 模板内的任何位置。

    <button data-bind="click: $root.saveMovie">Save</button>
    
  2. 第二步。将saveMovie方法添加到视图模型

    self.saveMovie = function(movie) {
        $.ajax({
            type: "POST",
            url: "/someurl",
            dataType: "json",
            contentType: "application/json",
            data: ko.toJSON(movie),
            success: function(result) {
                //...
            }
        });
    }
    

movie变量将包含 foreach 循环的项!为什么?因为在 Knockout 中,我们有一个惊人的功能,称为绑定上下文:

绑定上下文是保存可引用的数据的对象 从您的绑定中。应用绑定时,自动挖空 创建和管理绑定上下文的层次结构。根级别 层次结构引用您提供给的视图模型参数 ko.applyBindings(viewModel).然后,每次使用控制流时 绑定(如 with 或 foreach),用于创建子绑定上下文 这是指嵌套视图模型数据。

http://knockoutjs.com/documentation/binding-context.html