简体   繁体   中英

How do you refer to a current element using knockout js?

I am having trouble accessing my stored 'locations' array. Locations is an object literal and I am trying to access the title property BASED on the current element I click. I have the following code but I can't get it to console.log it properly. My guess is that my usage of 'this' and closure functions are not strong. Hopefully I explained this well enough in order for someone to shed some light. Any feedback + explanations are extremely appreciated.

(Sidenote: My project requirements say that I need to use knockout JS framework and the MVVM format)

  1. HTML

  <ul data-bind="foreach:locationsArray, click:goToLocation"> <li><span id="place" data-bind="text:title"></span></li> </ul> 

2) Javascript ViewModel

var ViewModel = function() {

  var self = this;

  self.locationsArray = ko.observableArray(locations);

  //My goal here is to log the current title of the location selected from the 
  //model. This is the part that is not working..
  self.goToLocation = function(self) {
    console.log(self.locations);
  }

3) Javascript data model (JSON format)

var locations = [
  {
    title: 'Nino\'s Pizza',
    location: {
      lat: 40.620057,
      lng: -74.032894
    }
  },
  {
    title: 'Shore Road Bike Path',
    location: {
      lat: 40.623089,
      lng: -74.040596
    }
  },
  {
    title: 'Paneantico Bakery',
    location: {
      lat: 40.619418,
      lng: -74.0322818
    }]

You need to attach the click event to the li not ul .

<ul data-bind="foreach:locationsArray">
  <li><span id="place" data-bind="text:title, click:$parent.goToLocation"></span></li>
</ul>

Here, $parent will tell knockout to look for a goToLocation in the ViewModel and not location object.

Then in your js:

var ViewModel = function() {
  var self = this;
  self.locationsArray = ko.observableArray(locations);

  // item will have the data of the clicked li
  self.goToLocation = function(item) {
    console.log(item);
  }
}

ko.applyBindings(new ViewModel());

Here's fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM