diff gpp/core/widgets.py @ 186:be3fff614b93

Implement #66; use jQuery UI autocomplete widget to replace obsolete jquery-autocomplete plugin. I implemented a very simple caching system.
author Brian Neal <bgneal@gmail.com>
date Tue, 30 Mar 2010 01:30:32 +0000
parents ab7830b067b3
children 5453aedf95fd
line wrap: on
line diff
--- a/gpp/core/widgets.py	Sun Mar 28 23:25:10 2010 +0000
+++ b/gpp/core/widgets.py	Tue Mar 30 01:30:32 2010 +0000
@@ -9,26 +9,47 @@
 
 
 class AutoCompleteUserInput(forms.TextInput):
-    class Media:
-        css = {
-            'all': settings.GPP_THIRD_PARTY_CSS['jquery-autocomplete'],
-        }
-        js = settings.GPP_THIRD_PARTY_JS['jquery-autocomplete']
 
     def render(self, name, value, attrs=None):
         url = reverse('core-ajax_users')
         output = super(AutoCompleteUserInput, self).render(name, value, attrs)
-        return output + mark_safe(u'''\
+        return output + mark_safe(u"""\
 <script type="text/javascript">
-jQuery("#id_%s").autocomplete("%s", {
-    width: 150,
-    max: 10,
-    highlight: false,
-    multiple: false,
-    scroll: true,
-    scrollHeight: 300,
-    matchContains: true,
-    autoFill: true
+$(function() {
+    var cache = {};
+    var cacheSize = 0;
+    $("#id_%s").autocomplete({
+        delay: 400,
+        minLength: 2,
+        source: function(request, response) {
+            if (cache[request.term]) {
+               response(cache[request.term]);
+               return;
+            }
+            $.ajax({
+                url: "%s",
+                type: "GET",
+                data: {
+                    q: request.term,
+                    limit: 10
+                },
+                dataType: "json",
+                success: function(data, textStatus) {
+                    if (cacheSize >= 16) {
+                       cache = {};
+                       cacheSize = 0;
+                    }
+                    cache[request.term] = data;
+                    ++cacheSize;
+                    response(data);
+                },
+                error: function(xhr, textStatus, ex) {
+                    alert('Oops, an error occurred. ' + xhr.statusText + ' - ' +
+                      xhr.responseText);
+                }
+            });
+        }
+    });
 });
-</script>''' % (name, url))
+</script>""" % (name, url))