如何数据绑定Knockout中接受参数的方法

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

本文关键字:参数 方法 数据绑定 Knockout      更新时间:2023-09-26

我正试图将当前对象作为参数传递给视图模型中的一个方法,但由于某种原因,我一直收到一个错误,表明该对象未定义。

我正在为Udacity前端网络开发纳米学位做一个社区地图项目。这个想法是使用谷歌地图api来显示一个城市,并在地图上填充各种位置的标记,以及所有位置的可过滤列表。可过滤列表中的位置应该是可点击的,并导致在与被点击的位置相对应的地图标记上进行一些操作。

我的问题是,当我点击列表中的一个位置时,我会得到以下错误:

Uncaught TypeError:无法读取未定义的属性"infowindow"_____self.openInfoWindow@app.js:95
_____(匿名函数)@knock-out3.1.0.js:67

这是我在Github中的项目链接
以下是相关的代码片段,供快速参考:

在HTML:中

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

在JS文件中:

//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);
      };

提前感谢任何能帮助我的人!

在GitHub repo中,您有一个self.points可观察数组,但没有self.point字段或可观察数组。我怀疑你是指

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

(点前无"自身")

此外,您的"point"类没有公开信息窗口。你需要这样做.infowindow而不是var infowindowhttps://github.com/Caoimhin89/Udacity_Project_5/blob/master/app.js#L21