简体   繁体   中英

How can I data-bind a method that takes an argument in Knockout?

I am trying to pass the current object as an argument to a method in my view model, but for some reason I keep getting an error suggesting that the object is undefined.

I am working on a neighborhood map project for the Udacity front-end web development nano degree. The idea is to use the google maps api to display a city and to populate that map with markers for various locations, as well as to have a filterable list of all the locations. The locations in the filterable list should be clickable and cause some action to take place on the map marker corresponding to the location being clicked.

My problem is that when I click on one of the locations in the list, I get the following error:

Uncaught TypeError: Cannot read property 'infowindow' of undefined _____self.openInfoWindow @ app.js:95
_____(anonymous function) @ knockout-3.1.0.js:67

Here is a link to my project in Github.
And here are the relevant pieces of code involved for quick reference:

In the HTML:

<tbody data-bind="foreach: {data: filterPoints, as: 'point'}">
  <tr>
    <td>
      <a href="#" data-bind="text: name, click: $parent.openInfoWindow"></a>
    </td>
  </tr>
</tbody>

In the JS file:

//create filter function so user can narrow the number of points in the list and on the map

      self.filterPoints = ko.computed(function() {
        var search = self.query().toLowerCase();
        return ko.utils.arrayFilter(self.points(), function(point) {
          var doesMatch = point.name().toLowerCase().indexOf(search) >= 0;
          point.isVisible(doesMatch);
          return doesMatch;
        });
      });

//create Google Maps infowindows for each point on the map

      self.openInfoWindow = function(point) {
        self.point.infowindow.open(map, point.marker);
        console.log(point);
      };

Thank you in advance to anyone who can help me out!

In your GitHub repo you have a self.points observable array but no self.point field or observable. I suspect you mean

point.infowindow.open(map, point.marker);
console.log(point);

(no "self." in front of point)

Also, your "point" class doesn't have the infowindow exposed. You'll need to do this.infowindow rather than var infowindow on https://github.com/Caoimhin89/Udacity_Project_5/blob/master/app.js#L21

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