淘汰映射选项;将JSON属性映射到两个视图模型属性

时间:2013-01-04 11:47:10

标签: javascript knockout.js knockout-mapping-plugin optimistic-concurrency

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

是否可以使用knockout映射插件,或者在填充视图模型后是否必须迭代映射的observable以获取副本?

1 个答案:

答案 0 :(得分: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());