0

I'm new working with Knockout.js framework and I'm having the following error in my code, I'm building an application using Knockout.js, everything works fine except when I tried to create a dependentObservable.

This is the javascript code:

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

The error in the chrome console is:

Uncaught TypeError: Cannot read property 'locations' of undefined

Jose Raul Perera
  • 778
  • 1
  • 7
  • 35

2 Answers2

1

You can't use 'app' var because you're still creating it.

var app = {... 

    ^^^    return ko.utils.arrayFilter(app.locations(), ...

                                       ^^^
Edilson Borges
  • 549
  • 4
  • 11
0

When using object literal for viewmodels, you should define your computed/dependent observables as

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

Notice passing of app object as second parameter to computed function that defines scope for this.

Also use computed instead of dependentObservable.

Computed Observables

Dandy
  • 2,177
  • 14
  • 16