Search code examples
javascriptknockout.jsknockout-mvc

data subscribed to Knockout ObservableArray but displaying empty array


I'm new to javascript. i'm having difficulty printing the data from the location ObservableArray. The data - bind works and i could list out the data from the location ObservableArray at the view but can't print it out on the console. i have been on it for hours now, any help would be appreciated. thank you

Here is the ViewModel

    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());

Here is the Binding Code`

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

LocationList

  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'
},
  ];

Solution

  • This can unwrap observable to regular js and convert this to single string (if needed) and then u can print it console :

    let locationsJSON = ko.toJS(self.location);
    let locationsString = JSON.stringify(locationsJSON);