1

アプリのクライアント側を構築するために、Knockout.js と datajs ライブラリ (OData をサポートするため) を備えた jQWidgets UI フレームワークを使用しています。サーバー側の ASP.NET Web API2 の OData エンドポイント。以下のコードのように、jqWidgets Grid の ViewModel を作成しました。

    var vm = function() {
        this.items = ko.observableArray();
        var self = this;

        //qet data from service 
        OData.read(url,
            function success(data, response) {
                //convert data to observable array
                self.items(data.results);
            },
            function error(err) {
                alert(err.message); 
            });


        this.removeItem = function() {
            // remove item
            var element = "#jqxgrid";
            var cell = $(element).jqxGrid('getselectedcell');
            if (cell != null && cell != "") {
                var selectedrowindex = cell.rowindex;
            };

            var item =$(element).jqxGrid('getrowdata', selectedrowindex);

            OData.request({
                requestUri: url + '(' + item.CompanyID + ')',
                method: "DELETE",
            },
            function success(data, response) {
                alert('DELETE successfull');
            },
            function error(err) {
                alert(err.message); 
            });
        };

ご覧のとおり、アイテムを取得および削除できます。私の問題は、すべての変更を保存し、変更されたアイテムだけをサーバーに送信する方法です。サーバー側でエンティティを追加/更新するには、適切な json オブジェクト (オブジェクトのコレクションではない) を使用して POST/PUT 要求を送信する必要があります。したがって、たとえば、変更されたすべてのアイテムを更新する場合は、アイテムごとに PUT リクエストを実行する必要があります。observableArray のどのアイテムが追加/変更されたかを検出し、それらの各アイテムをサーバーに送信する方法はありますか??

4

1 に答える 1

1

ノックアウトは、そのままではこれを行いません。私が過去に行ったことは、配列に格納されているオブジェクトに isDirty フラグを設定することです (これは、オブジェクトにオブザーバブルが設定されていることを前提としていますが、これが機能しない場合、通常の js オブジェクトを使用して簡単に実行する方法はありません)。is dirty フラグは監視可能なプロパティの変更を監視し、オンになるとフラグを true に設定します。次に、保存が行われているときに、 isDirty() == true のレコードかどうかを確認します

var entryForm = function(){
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.email = ko.observable();
self.dirty = ko.observable(false);
self.dirtyCalculations = ko.computed(function(){
    //read from any observable we want to watch as part of our "dirty" calculation
    self.firstName();
    self.lastName();
    self.email();

    //if any of the above changed, this method will be called, so this model is now "dirty"
    self.dirty(true);
});

//see the next section for an explanation of these lines
self.resetDirtyFlag = function(){self.dirty(false);}
self.resetDirtyFlag();
}

上記のコードでは、プロパティをオブザーバブルに変換せずに、戻りオブジェクトを配列に直接接続していることがわかります。プロパティを変換し、上記の同様の方法を使用することをお勧めします。

于 2014-03-26T12:30:15.907 に答える