Knockout 映射插件未在模型内映射数组
我试图将一些数据(从 jQuery $.ajax 调用返回)映射到视图模型,但由于某种原因,嵌套数组未映射。
<p>Name: <input data-bind="value: Name" /></p>
<p>Age: <input data-bind="value: Age" /></p>
<p>Friends: <span data-bind="text: Friends.length"></span></p>
<script type="text/javascript">
var viewModel = null;
var data = { "Name": "Simon", "Age": "24", "Friends": [{ "Name": "Bill", "Age": "24" }, { "Name": "Peter", "Age": "21"}]};
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
</script>
在这个简单的例子中,西蒙没有朋友......
I'm trying to map some data (returned from a jQuery $.ajax call) to a view model, but for some reason the nested array is not mapped.
<p>Name: <input data-bind="value: Name" /></p>
<p>Age: <input data-bind="value: Age" /></p>
<p>Friends: <span data-bind="text: Friends.length"></span></p>
<script type="text/javascript">
var viewModel = null;
var data = { "Name": "Simon", "Age": "24", "Friends": [{ "Name": "Bill", "Age": "24" }, { "Name": "Peter", "Age": "21"}]};
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
</script>
In this simple example Simon has no friends...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
mapping.fromJS 将数组转换为可观察数组,因此 Friends 是一个可观察数组,要访问其底层 javascript 数组,您需要调用它:Friends().length
mapping.fromJS converts arrays to observable arrays, so Friends is an observable array and to access its underlying javascript array you need to call it: Friends().length