javascript - 订阅了 Knockout ObservableArray 但显示空数组的数据
问题描述
我是 JavaScript 新手。我很难从位置 ObservableArray 打印数据。数据绑定有效,我可以在视图中列出来自 ObservableArray 位置的数据,但无法在控制台上打印出来。我已经做了几个小时了,任何帮助将不胜感激。谢谢你
这是视图模型
let MapViewModel = function() {
let map
let geocoder;
let self = this;
self.location = ko.observableArray([]);
for (let i = 0; i < locationList.length; ++i) {
self.location.push(new Location(locationList[i]));
}
console.log(this.location()); // Location, Location, Location, Location, Location, Location, Location]
console.log(this.location()[0].name); // Location {name: ƒ, address: ƒ} ...
console.log(this.location().length); //length is 7
}
let Location = function(data) {
this.name = ko.observable(data.name);
this.address = ko.observable(data.address);
}
ko.applyBindings(new MapViewModel());
这是绑定代码`
<div class="menu_item_container">
<h1>Neighborhood Map</h1>
<input type="text" id="search" data-bind= 'value:filterLocations, valueUpdate: 'afterKeyDown',value:filterLocations' placeholder="Search Locations...">
<hr>
<nav id=nav>
<ul data-bind='foreach:location'>
<li data-bind="text:name"></li>
</ul>
</nav>
</div>
位置列表
let locationList = [{
name: 'Brooklyn Museum',
address: '200 Eastern Pkwy, Brooklyn, NY 11238'
}, {
name: 'Empire State Building',
address: '350 5th Ave, New York, NY 10118'
}, {
name: 'Statue of liberty',
address: 'New York, NY 10004'
}, {
name: 'Rockefeller Center',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'Brooklyn Bridge',
address: 'Brooklyn Bridge, New York, NY 10038'
},
{
name: 'Time Square',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'World Trade Center',
address: '285 Fulton St, New York, NY 10007'
},
];
解决方案
这可以将 observable 解包为常规 js 并将其转换为单个字符串(如果需要),然后您可以在控制台打印它:
let locationsJSON = ko.toJS(self.location);
let locationsString = JSON.stringify(locationsJSON);
推荐阅读
- java - 新的 Elastic Beanstalk 环境不打印到日志
- python-3.x - django 功能的 rdb 与键值存储
- php - 当通过 php 重定向使用 get 方法时,如何显示 php 变量的值而不是 php 变量的名称。预流行
- git - 你如何在 Sourcetree/Git 中合并一大堆的分支?
- python - 运行流畅,但输出不正确
- c - 什么 register const char *const *name; 意思是为什么这个变量在函数之外?
- asp.net-core - 如何解决 Linux Mint 20 上的 nuget 错误 SSL 连接?
- kubernetes - 一个对一个节点的标签有亲和力但不容忍该节点的污点的 Pod 是否可以挂载到该节点?
- javascript - 如何在抓取网站时不断收听新项目
- arduino - 为什么ledstrip中途停止然后一直走,我可以让这个更有效率吗