【问题标题】:Knockout.js -Getting error - Uncaught ReferenceError: Unable to process binding "with: function"Knockout.js - 出现错误 - 未捕获的 ReferenceError:无法处理绑定“with:function”
【发布时间】:2017-04-19 22:44:05
【问题描述】:

我正在做一个社区地图项目,但我被困住了!我是 knockout.js 的新手。我正在尝试使用数据绑定得到这个错误 -

knockout-3.4.1.js:72 Uncaught ReferenceError: Unable to process binding "with: function (){return filteredItems }"

HTML源码的sn-p -

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

【问题讨论】:

  • locations 中的 self.items = ko.observableArray(locations); 是什么?
  • locations 是一个包含位置名称及其坐标(纬度 lng 值)的数组。我已经给出了我的 github repo 的链接。
  • 这行不应该是:return stringStartsWith(id.name.toLowerCase(), self.filter);return stringStartsWith(id.name.toLowerCase(), filter); (没有self

标签: javascript jquery html knockout.js


【解决方案1】:

with 绑定使用提供的元素创建一个新的绑定上下文。由于在&lt;span&gt; 元素中引用了title,而引发了错误,但filteredItems 没有title 属性。

如果您想为filteredItems 数组中的每个元素显示一个&lt;li&gt; 元素,您可以使用foreach 绑定,如下所示:

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

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 2017-01-10
    • 2022-01-15
    • 2014-09-18
    • 1970-01-01
    • 2020-05-06
    • 2023-04-01
    • 2013-08-03
    • 2020-05-03
    相关资源
    最近更新 更多