我从Knockout的View Model调用Foursquare API。 我没有收到任何错误,但我在网络标签中看到没有调用API的迹象。
我是否需要添加特定代码才能在View Model中调用API?
var ViewModel = function(){
console.log("View Model started")
var self = this;
// Foursquare API Call :
self.venueList = ko.observableArray([
]);
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()
{
console.log("API called");
$.getJSON(foursquareURL, function(data){
//Add a header
$foursquareElem.text('Croissants');
var venues = data.response.venues;
self.venueList = ko.observableArray([]);
for (var i=0; i<venues.length; i++){
console.log(venues[i].name);
self.venueList.push ({
name: venues[i].name,
lat: venues[i].location.lat,
lng: venues[i].location.lng
});
console.log(self.venueList()[i].name)
}
}).error(function() {
$foursquareElem.text( "No data available" );
});
};
};
ko.applyBindings(new ViewModel());
HTML:
<div id="foursquare-venues">
<ul data-bind= "foreach:venueList">
<li id="li-name" data-bind = "text: $data.name">
</li>
答案 0 :(得分:0)
如评论中所述
请确保您声明observable / observableArray一次并重新使用它。避免重复声明,因为你在getJSON中有这样的声明。