Question

I'm currently learning knockout and are currently experimenting with the various things that can be achieved with the library. One thing I'm trying to do right is to create a 'live search'. (codepen below)

The error i'm getting is cannot read propery 'toLowerCase' of undefined. To me, my code looks right and I'm guessing there's a rookie error somewhere.

The data in self.tracks() is fetched from soundcloud and pushed into an observableArray. My HTML template renders these tracks perfectly fine if I remove all instances of 'computedTracks' - it's looking like the function can't read self.tracks()?

HTML:

<input placeholder="Search..." type="search" data-bind="value: searchQuery">

<div class="view-tracks">
    <ul data-bind="foreach: computedTracks">
        <li data-bind="click: $root.goToTrack">
            <span data-bind="text: track"></span>
        </li>
    </ul>
</div>

KO:

self.computedTracks = ko.computed(function() {
                return ko.utils.arrayFilter(self.tracks(), function(item) {
                    return item.track.toLowerCase().indexOf(self.searchQuery().toLowerCase()) >= 0;
                });
            });

If anybody could highlight my error in this it would be much appreciated.

Complete demo:

http://codepen.io/anon/pen/EHgdx

Was it helpful?

Solution

CodeOpen

The problem is that your initial value for the searchQuery observable is set to undefined. You either have to check if it is defined and then call toLowerCase() or set a default value of '' for it. Just like I did in the codeopen demo.

self.searchQuery = ko.observable('');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top