-1

为了在将(可能)修改后的视图模型发布/保存回服务器时进行乐观并发检查,我想在一个单独的变量中获取原始值的副本,而不是使用淘汰绑定绑定到的可观察变量。

这可能与淘汰映射插件有关,还是在填充视图模型后我必须遍历映射的可观察对象以获取副本?

4

1 回答 1

0

这个怎么样?

function Task(data) {
    var self = this;
    self.title = ko.observable(data.title);
    self.origTitle = data.title;
    self.isDone = ko.observable(data.isDone);
    self.origIsDone = data.isDone;

    self.changes = ko.computed(function() {
        var changed = [];

        if (self.title() != self.origTitle) changed.push({ self.title(), self.origTitle });
        if (self.isDone() != self.origIsDone) changed.push({ self.isDone(), self.origIsDone });
        return changed;
    });
}

function TaskListViewModel() {
    // Data
    var self = this;
    self.tasks = ko.observableArray([]);
    self.newTaskText = ko.observable();
    self.changes = ko.computed(function() {
        var tasksToPost = ko.utils.arrayFilter(self.tasks(), function(task) { return task.changed().length > 0 });            
        $.ajax({
            type: 'POST',
            url: '/SomeUrl',
            data: tasksToPost 
        });
    });

    // Operations
    self.addTask = function() {
        self.tasks.push(new Task({ title: this.newTaskText() }));
        self.newTaskText("");
    };
    self.removeTask = function(task) { self.tasks.remove(task) };

    // Load initial state from server, convert it to Task instances, then populate self.tasks
    $.getJSON("/tasks", function(allData) {
        var mappedTasks = $.map(allData, function(item) { return new Task(item) });
        self.tasks(mappedTasks);
    });    
}

ko.applyBindings(new TaskListViewModel());
于 2013-01-04T11:55:49.107 回答