Best way to get only modified rows from observableArray (when there is bulk edit option)

后端 未结 2 1955
感动是毒
感动是毒 2021-02-10 05:54

I have an ObservableArray collection which binds to the HTML table with bulk edit option (MVC3), every time the user hits commit I wanted to send only the modified

2条回答
  •  遇见更好的自我
    2021-02-10 06:11

    It it not so trivial task as it may looks like.

    At first, observable array only handles modification of array (insert, remove, reorder etc.) not modification of element.

    At second, you would probably need special flag like 'isModified' in your model that binds to each table row.

    Then you need to set that flag if some of the binding was updated. Knockoutjs observables provides method subscribe that allows to call your own function when observables is updated. Take a look at page http://knockoutjs.com/documentation/observables.html at the bottom there is a section called 'explicitly subscribe to observables'.

    There is a quick draft of code that performs that task

    function CreateArrayElementViewModel(inputData) {
         // Creating our view model
         var result = {
               prop : ko.observable(inputData.prop),
               val : ko.observable(inputData.val),
               isModified: false // This property would be true if entity was edited
         };     
         // Iterate over all properties and subscribe to knockoutjs observables
         for(prop in result) {
              if (typeof(result[prop].subscribe) != 'undefined') {
                   result[prop].subscribe(function() { result.isModified = true; });
              }
         }
    
         return result;
    }
    

提交回复
热议问题