gutch
gutch

Reputation: 7139

How can live search / search suggestions be implemented using Dojo?

I want to implement a 'live search' or 'search suggestions' feature in a web application that uses the Dojo Framework. It would be similar to the way Google and Bing searches display matches as you type: when you type in the search box, a list of potential matches appears below. Searches would be performed server side, with the results sent back to the browser using AJAX.

Does anyone know of a good way to implement this using Dojo?

Here are some potential options:

I could probably make one of the above work, but I'd like to know if there are any better alternatives out there.

Upvotes: 22

Views: 2602

Answers (1)

Eugene Lazutkin
Eugene Lazutkin

Reputation: 43956

I implemented it 5 years ago when Dojo was at 0.2:

While the code is ancient, it is trivial, and hopefully it'll give you ideas on how to attack it. The rough sketch:

  • Attach an event handler to your input box, which is triggered on changes — use "onkeyup" to detect a change in the input box.
  • Wait until user stopped typing by setting a timer in your event handler, if it is not set yet. 200-500ms are good waiting times.
    • The timeout plays a dual role:
      • It throttles our requests to a server to prevent overloading.
      • It plays on our perception of time and our typing habits.
  • If our timeout is up, and we don't wait for a server ⇒ send server a string we have so far.
  • If we are still waiting for a server, cancel the request and ask again.
    • This part is app-specific: we don't want to overload a server, and sometimes a server cannot handle broken connections well.
    • In the example I don't cancel the XHR call, but wait it to finish first before submitting new request.
  • Server responds with relevant results, which are promptly shown.

In the blog post I implemented it as a widget. Obviously the exact packaging is up to you.

Upvotes: 11

Related Questions