Knockout.js -Getting error - Uncaught ReferenceError:无法处理绑定" with:function"

时间:2016-12-05 13:58:04

标签: javascript jquery html knockout.js

我正在制作一个邻居地图项目,我被困住了!我是knockout.js的新手。我试图使用data-bind获取此错误 -

knockout-3.4.1.js:72 Uncaught ReferenceError:无法处理绑定" with:function(){return filteredItems}"

HTML源代码片段 -

section class="main">
          <form class="search" method="post" action="index.html" >
            <input type="text" data-bind="textInput: filter" placeholder="Click here/Type the name of the place">
            <ul data-bind="with: filteredItems">
              <li><span data-bind="text: title, click: $parent.showInfoWindow"></span></li>
            </ul>
         </form>
        </section>

这是我的viewModel -

function viewModel(markers) {
  var self = this;
  self.filter = ko.observable(''); // this is for the search box, takes value in it and searches for it in the array
  self.items = ko.observableArray(locations); // we have made the array of locations into a ko.observableArray
  // attributed to - http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html , filtering through array
  self.filteredItems = ko.computed(function() {
    var filter = self.filter().toLowerCase();
    if (!filter) {
      return self.items();
    } else {
      return ko.utils.arrayFilter(self.items(), function(id) {
        return stringStartsWith(id.name.toLowerCase(), self.filter);
      });
    }

  });

  var stringStartsWith = function (string, startsWith) {
       string = string || "";
       if (startsWith.length > string.length)
           return false;
       return string.substring(0, startsWith.length) === startsWith;
   };
  // populateInfoWindow(self.filteredItems,)


  // this.showInfoWindow = function(place) { // this should show the infowindow if any place on the list is clicked
  //     google.maps.event.trigger(place.marker, 'click');
  // };

}

有些行被评论,因为我还在努力。要查看整个项目 - https://github.com/Krishna-D-Sahoo/frontend-nanodegree-neighborhood-map

1 个答案:

答案 0 :(得分:3)

with绑定使用提供的元素创建新的绑定上下文。由于在title元素中引用<span>,但filteredItems没有title属性,因此引发错误。

如果要为<li>数组中的每个元素显示filteredItems元素,可以使用foreach绑定,如下所示:

<ul data-bind="foreach: filteredItems">
  <li><span data-bind="text: title, click: $parent.showInfoWindow"></span></li>
</ul>