KnockoutJS-更新ViewModel/映射插件 [英] KnockoutJS - Update ViewModel / Mapping Plugin
问题描述
- 在页面加载时,我得到一个模型,并使用
ko.mapping.fromJS(myObject)
将其转换为viewModel. - 如果用户单击按钮,我想从服务器获取更新的数据
- 现在我要应用这些更新
- On page load i get a Model and convert that using
ko.mapping.fromJS(myObject)
to a viewModel. - If the user clicks a button i want to get updated data from the server
- Now i want to apply theese updates
如果我使用ko.applyBindings(viewModel);
,它将完美地更新ui.但是,它再次添加了相同的事件.因此,如果用户单击该按钮,则事件将被触发两次,第三次,依此类推.
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.
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();
});
更新
Steve Greatrex 您可以发布自定义绑定实现吗?
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;
},
};
推荐答案
如果您查看映射文档,您可以为映射指定目标.
If you look at the 'Specifying the update target' on the mapping documentation, you can specify a target for the mapping.
这应该意味着您可以说:
This should mean that you can say:
if (!viewModel)
viewModel = ko.mapping.fromJS(data);
else
ko.mapping.fromJS(data, {}, viewModel);
这样,您将在初始加载时创建视图模型,然后为以后的所有加载更新该视图模型.
This way you will create a view model on the initial load, then update that view model for any subsequent loads.
这篇关于KnockoutJS-更新ViewModel/映射插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!