仅从ko.observableArray发送更新的对象

时间:2017-05-18 11:32:00

标签: javascript mvvm knockout.js knockout-validation knockout-3.0

如何从可观察的数组中仅发送更新的模型而不是发送整个数组?

var student = function (){
    this.studentId=0;
    this.firstName=ko.obserable();
    this.lastName=ko.obserable();
}
var course= function (){
    this.courseId=0;
    this.students=ko.obserableArray([]);
    this.Name=ko.obserable();
}

现在我想只获得那些信息更新的特定学生。假设当我们添加一个新类时,我们可以随时随地动态添加新学生。假设您必须在添加新学生之前验证之前的学生。当我得到那个特定的学生时,我想将该学生信息发送回服务器。

感谢。

2 个答案:

答案 0 :(得分:0)

如果我理解您的任务正确,您可以使用“arrayChange”事件类型来获取确切更改(添加/删除)的项目:

sourceArray = ko.observableArray();
sourceArray.subscribe(function (changes) {
        changes.forEach(function(arrayChange) {
            if(arrayChange.status === 'added') {
                // some code on add
            } else if(arrayChange.status === 'deleted') {
                // some code on delete
            }
        });
    }, null, "arrayChange");

答案 1 :(得分:0)

如果要获取已修改的学生列表,可以提供一个标记来标识是否已在学生对象中修改了对象。每当更新值时,使用.subscribe修改该标志。然后使用ko.computedko.pureComputed获取该列表。

它也假设为observable



var student = function (id, firstName, lastName) {
  var self = this;
  self.hasChanged = ko.observable(false);
  var modified = function(){
    self.hasChanged(true);
  };

  self.studentId = ko.observable(id);
  self.firstName = ko.observable(firstName);
  self.firstName.subscribe(modified);
  self.lastName = ko.observable(lastName);
  self.lastName.subscribe(modified);
}
var course= function (){
  var self = this;
  self.courseId = 0;
  self.students = ko.observableArray([new student(1, "Cristiano", "Ronaldo"), new student(2, "Lionel", "Messi")]);
  self.modifiedStudent = ko.computed(function(){
    return ko.utils.arrayFilter(self.students(), function(student) {
        return student.hasChanged();
    });
  }, self);
  self.Name = ko.observable("Programming 101");
}  

$(document).ready(function () {
  var myViewModel = new course();
  ko.applyBindings(myViewModel);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

List of all students:
<div data-bind="foreach: students">
  <div>
    <span data-bind="text: studentId"></span>
    <input type="text" data-bind="value: firstName" />
    <input type="text" data-bind="value: lastName" />
  </div>
</div>
<br/>

List of students which has been modified:
<div data-bind="foreach: modifiedStudent">
  <div>
    <span data-bind="text: studentId"></span>
    <input type="text" data-bind="value: firstName" readonly />
    <input type="text" data-bind="value: lastName" readonly />
  </div>
</div>
&#13;
&#13;
&#13;