我很难看出我的代码有什么问题。更有可能是 Knockout.js 部分......它给了我以下错误:
Message: Unable to process binding "attr: function (){return {href:website()} }"
HTML
<div class="demo-card-square mdl-card mdl-shadow--2dp" data-bind="foreach: favoriteSpot">
<div class="mdl-card__title mdl-card--expand">
<h2 class="mdl-card__title-text">Update</h2>
</div>
<div class="mdl-card__supporting-text" data-bind="text:name"></div>
<div class="mdl-card__supporting-text" data-bind="text:location"></div>
<a data-bind="attr: {href: website()}">Website</a>
</div>
JS
var favoriteSpotsList = [{
venueName: "name",
venueLocation: "address",
website: "url",
image: "<img src='img'",
}];
var favoriteSpot = function(data) {
this.name = ko.observable(data.venueName);
this.address = ko.observable(data.venueLocation);
this.website = ko.observable(data.website);
this.image = ko.observable(data.img);
};
var AppViewModel = function() {
var self = this;
/* Create array of hotspot locations. */
this.hotSpotList = ko.observableArray([]);
favoriteSpotsList.forEach(function(spot) {
self.hotSpotList.push(new favoriteSpot(spot));
});
};
ko.applyBindings(new AppViewModel());
最佳答案
正如 @saj
和 @haim770
在评论中提到的, View 模型上没有 favoriteSpot
属性。因此,数据绑定(bind)应该循环 hotSpotList
以获取其中的网站属性。如下图,
data-bind="foreach: hotSpotList"
有一种简单的方法可以识别这类问题,特别是在 View 中执行绑定(bind)时
你只需要添加一个带有点击绑定(bind)的按钮,按钮应该放在异常行之前。
<button data-bind="click: function () { console.log($context); }"> Context Log </button>
以上代码将在浏览器控制台(F12)
中记录整个上下文。像往常一样你会得到异常(exception)。并且此代码不会解决问题。但这将非常有助于确定问题。
以上代码将记录当前操作的整个上下文
。其中包含具有值的对象、属性。
下面是常见的场景,您可以准确地发现您的绑定(bind)对象有异常。
1。由于范围级别问题,属性存在/缺失?
2。是否有区分大小写的问题?
3。你的对象在哪里?是 parent 、 child 还是一个人?
4。绑定(bind)时出现异常的人为错误。
很少有其他方法可以找到 View 中的对象/数据:
1。记录根目录:
<button data-bind="click: function () { console.log($root); }"> Root Log </button>
2。记录当前作用域数据:
<button data-bind="click: function () { console.log($data); }"> Current Data Log </button>
3。记录父数据:(当我们进行循环时特别有用)
<button data-bind="click: function () { console.log($parent); }"> Parent Log </button>
4。记录父数据列表:(当我们对不同类型的父进行循环时特别有用)
<button data-bind="click: function () { console.log($parents); }"> Parents Log </button>
5。记录父数据列表:(当我们循环访问不同类型的父数据时特别有用)
<button data-bind="click: function () { console.log(objectName.propertyName); }">Property Log </button>
例如,在您的情况下,您可以执行以下操作:
<!-- Added this button before the exception -->
<button data-bind="click: function () { console.log(favoriteSpot); }">Log </button>
<div class="demo-card-square mdl-card mdl-shadow--2dp" data-bind="foreach: favoriteSpot">
<div class="mdl-card__title mdl-card--expand">
<h2 class="mdl-card__title-text">Update</h2>
</div>
<div class="mdl-card__supporting-text" data-bind="text:name">
</div>
<div class="mdl-card__supporting-text" data-bind="text:location">
</div>
<a data-bind="attr: {href: website()}">Website</a>
</div>
当您单击该按钮时,显然该消息将在控制台中记录为 undefined
。
希望对您有所帮助,
关于javascript - knockout 错误 - 无法处理绑定(bind) “foreach”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489901/