9

How can i update the complete viewModel ?

  1. On page load i get a Model and convert that using ko.mapping.fromJS(myObject) to a viewModel.
  2. If the user clicks a button i want to get updated data from the server
  3. Now i want to apply theese updates

If i use ko.applyBindings(viewModel); it updates the ui perfectly. But it adds the same events again. So if the user clicks the button, the event gets fired twice, third and so on.

Question

What is a good way to update my complete viewModel. Maybe i remove the bindings and apply them again ? (how to do this).

Sample

var viewModel;

function update() 
{
    $.ajax({
        url: '...',
        type: "GET",
        statusCode: {
            200: function (data) {
                 viewModel = ko.mapping.fromJS(data);
                 ko.applyBindings(viewModel);
            }
        }
    });    
}

// first call after page load
update();

// user click
$("#myButton").click(function() {
    update(); 
});

Update

Steve Greatrex Could you post your custom binding implementation?

ko.bindingHandlers.domBinding = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        viewModel.domElement = element;
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        viewModel.domElement = element;
    },
};
4

2 回答 2

10

如果您查看映射文档中的“指定更新目标” ,您可以为映射指定一个目标。

这应该意味着你可以说:

if (!viewModel)
   viewModel = ko.mapping.fromJS(data);
else
   ko.mapping.fromJS(data, {}, viewModel); 

这样,您将在初始加载时创建一个视图模型,然后为任何后续加载更新该视图模型。

于 2012-08-02T13:43:46.663 回答
3

使用映射插件我做到了

ko.mapping.fromJS(JsonResponse, myObservable());

就这样。

于 2012-09-27T17:27:23.403 回答