我正在使用 JS Knockout 显示来自 Four Square API 的搜索结果。 我的 Javascript 代码中有这个 View 模型
var ViewModel = function(){
var self = this;
// Foursquare API Call :
this.foursquareURL = 'https://api.foursquare.com/v2/venues/search?ll=37.8,-122.4&query=croissant&client_id=CLIENT_ID&client_secret=CLIENT_SECRET';
this.fs_ApiCall = function()
{
$.getJSON(foursquareURL, function(data){
$foursquareElem.text('Get a croissant');
var venues = data.response.venues;
self.venueList = ko.observableArray([]);
for (var i=0; i<venues.length; i++){
self.venueList.push ({
name: venues[i].name,
lat: venues[i].location.lat,
lng: venues[i].location.lng
});
}
}).error(function() {
$foursquareElem.text( "No data available" );
});
};
};
ko.applyBindings(new ViewModel());
这就是我在 HTML 文档中应用绑定(bind)的方式
<div id="foursquare-venues">
<ul data-bind= "foreach:venueList">
<li id="li-name" data-bind = "text:name">
</li>
</ul>
未捕获的ReferenceError:无法处理绑定(bind)“foreach:function(){returnvenueList}” 消息:venueList 未定义
我不确定我是否使用了正确的方法在 API 中推送 API 响应,但错误消息似乎表明该数组甚至没有定义(?) 我不确定这里出了什么问题。
最佳答案
这是因为您在 getJSON 回调中实例化了 venueList
,该回调在应用绑定(bind)后调用。
你应该这样做:
var ViewModel = function() {
var self = this;
self.venueList = ko.observableArray([]); // instanciate here
// Foursquare API Call :
this.foursquareURL = 'https://api.foursquare.com/v2/venues/search?ll=37.8,-122.4&query=croissant&client_id=CLIENT_ID&client_secret=CLIENT_SECRET';
this.fs_ApiCall = function() {
$.getJSON(foursquareURL, function(data) {
// you might want to clear venueList here
$foursquareElem.text('Get a croissant');
var venues = data.response.venues;
for (var i = 0; i < venues.length; i++) {
self.venueList.push({
name: venues[i].name,
lat: venues[i].location.lat,
lng: venues[i].location.lng
});
}
}).error(function() {
// and here
$foursquareElem.text("No data available");
});
};
};
ko.applyBindings(new ViewModel());
关于javascript - knockout.js 可观察数组,错误 "Uncaught ReferenceError: Unable to process binding ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506903/