Knockout.js从View Model调用API

时间:2016-05-29 23:19:50

标签: javascript json knockout.js

我从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>

1 个答案:

答案 0 :(得分:0)

如评论中所述

请确保您声明observable / observableArray一次并重新使用它。避免重复声明,因为你在getJSON中有这样的声明。

相关问题