in JavaScript

Auto complete search with Knockout

Share on Facebook0Tweet about this on TwitterShare on LinkedIn0Share on Google+0Email this to someone

I’m starting to like knockout more and more.
We have used it for a while now in my project at work, and when I start something new that will be on the web I always end up with Knockout these days.

The other day I got a task: ”We want an autocomplete search”. Not a big deal, I first combined a knockout binding with jqueryUI’s autocomplete, and then the fun started.
My first question against this was, do I really need jQueryUI? And why do we have it in our project (couldn’t think of any part of the solution that used jQueryUI).

So I wrote my own binding, a knockout binding for a input element, that’s doing an ajax request to the server and showing the result down below the element. The source code with a example project can be found at github: Knockout Autocomplete

You can get the binding from nuget, simply run the install command with KnockoutAutocomplete as name:

install-package-autocmplete

The package will give you a small CSS file and a js file for the binding, the js file looks something like this:

It’s quite simple to use.

After you have installed the package, reference the js and css file that was installed by the package.
Add an element that uses the binding: (Configuration) A url that should return a list of json. Items should contain a ”id” property and a ”label” property, a selectCallback function that will be executed when clicking (selecting a item)

Add a observable property for your viewmodel self.search = ko.observable(”).extend({ throttle: 300 });
Adding a throttle so we dont make a request to the server each keypress
Add a function to your viewmodel that will be executed when clicking ( selecting an item) self.selectItemCallback = function(data) { //dosomething with the selected item console.log(data); }

Done and Enjoy!

If you have any toughts or comments let me know, either here, my Github page or Twitter.

Share on Facebook0Tweet about this on TwitterShare on LinkedIn0Share on Google+0Email this to someone

Write a Comment

Comment

  1. When I install the nuget package to a .net core application I cannot seem to find the files. I have manually included them. Just letting your know.

    Thanks.