带有敲除.js的过滤器绑定问题


我是使用Knockout.js

框架的新手,我的代码中遇到了以下错误,我正在使用Knockout.js构建一个应用程序,除了我尝试创建dependentObservable之外,一切正常。

这是javascript代码:

(function() {
  'use strict';
    console.log("This is my Application");
     var app = {
         mapElement: document.getElementById('map'),
         mapObj: map,
         locations : ko.observableArray([
            {id: 1, title: 'Holywood Theater', location: {lat: 43.098344, lng: -76.145697}},
            {id: 2, title: 'Mattydale Fire Department', location: {lat: 43.098172, lng: -76.142189}},
            {id: 3, title: 'Original Italian Pizza', location: {lat: 43.098854, lng:  -76.144700}},
            {id: 4, title: 'Roxboro Road Middle School', location: {lat: 43.101110, lng: -76.150901}},
            {id: 5, title: 'Big Lots', location: {lat: 43.101400, lng: -76.146985}},
            {id: 6, title: 'Camnel pub', location: {lat: 43.098670, lng: -76.145832}}
        ]),
        markers:[],
        textFilter: ko.observable(),
        filterLocations: ko.dependentObservable(function () {
                            return ko.utils.arrayFilter(app.locations(), function (loc) {
                                return loc.title().toLowerCase().includes(app.textFilter().toLowerCase());
                            });
                        })
     };
    ko.applyBindings(app);
})();

版式控制台中的错误是:

捕获的类型错误:无法读取未定义的属性"位置">

你不能使用'app' var,因为你仍在创建它。

var app = {... 
    ^^^    return ko.utils.arrayFilter(app.locations(), ...
                                       ^^^

对视图模型使用对象文本时,应将计算/依赖可观察量定义为

app.filterLocations = ko.computed(function () {
                        return ko.utils.arrayFilter(this.locations(), function (loc) {
                            return loc.title.toLowerCase().includes(app.textFilter().toLowerCase());
                        });
                    }, app);

请注意app对象作为第二个参数传递给定义this作用域的计算函数。

也使用 computed 而不是 dependentObservable .

计算可观察量

最新更新