我有以下与我合作的简单案例:
<ul data-bind='template: {name : "namesTemplate", data:viewModel}'>
</ul>
<script id='namesTemplate' type='text/html'>
{{each $data}}
<li>${ Name }</li>
{{/each}}
</script>
<span data-bind="click: fire">Click Me</span>
<script type='text/javascript'>
var viewModel = ko.observableArray([{ "Name": "Tom" },
{ "Name": "Pete" },
{ "Name": "Dave"}]);
viewModel.fire = function () {
$.getJSON("Post", function (result) {
viewModel = ko.mapping.fromJSON(result);
});
}
ko.applyBindings(viewModel);
</script>
getJSON
从ASP.NET MVC控制器获取JSON数据,类似于:
[{"Name":"Chris"}]
单击单击我后,无序列表未更新。我哪里错了?
感谢。
答案 0 :(得分:2)
两个想法:
1)在视图模型上命名您的属性:
var viewModel = { employees: ko.observableArray([{ "Name": "Tom" },
{ "Name": "Pete" },
{ "Name": "Dave"}]);
};
2)由于您的视图模型中已有数据,您可能应该使用 ko.mapping.updateFromJS :
viewModel.fire = function () {
$.getJSON("Post", function (result) {
ko.mapping.updateFromJS(viewModel.employees, result);
});
}
答案 1 :(得分:0)
看看我的例子:
var viewModel ={
names: ko.observableArray([{ "Name": "Tom" },
{ "Name": "Pete" },
{ "Name": "Dave"}])
};
viewModel.fire = function() {
this.names([{"Name": "test"}]);
};
ko.applyBindings(viewModel);
和Html:
<ul data-bind='template: {name : "namesTemplate", foreach:names}'></ul>
<span data-bind="click: fire">Click Me</span>
<script id='namesTemplate' type='text/html'>
<li data-bind="text: Name"/>
</script>
如果您想添加新阵列,可以使用push方法:
this.names.push([{"Name": "test"}]);