summaryrefslogtreecommitdiffstats
path: root/public/javascripts/live_search.js
blob: f13c35b71518682e51bfa6764f1ac8952da152c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/*
  #--
  #   Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
  #
  #   This program is free software: you can redistribute it and/or modify
  #   it under the terms of the GNU Affero General Public License as published by
  #   the Free Software Foundation, either version 3 of the License, or
  #   (at your option) any later version.
  #
  #   This program is distributed in the hope that it will be useful,
  #   but WITHOUT ANY WARRANTY; without even the implied warranty of
  #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  #   GNU Affero General Public License for more details.
  #
  #   You should have received a copy of the GNU Affero General Public License
  #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  #-- 
*/
/*
  Creating a jquery extension
*/
jQuery.fn.liveSearch = function(backend, options) {
    // Set some options
    options = jQuery.extend({
        resultContainer: ".live-search-results",
        backend: this.backend,
        waitingClass: "waiting",
        resourceUri: "/foo/bar",
        delay: 250,
        itemCass: "result",
        renderer: {render: function (obj) {
            return jQuery("<li class=\"item\">" + obj.name + "</li>")}}
    }, options);

    var element = this, // Keep this, ie. where this is started, as element
    container = element.find(options.resultContainer),  // Where the results go
    timer,  // Timing to avoid parallell searches
    previous,  // The last search term
    input = element.find("input[type=text]"),  
    uri = options.resourceUri + "?" + input.attr("name") + "=",
    resetter,
    noResults = element.find(".no-results-found");  
    
    // Create the container element if it doesn't exist
    if (container.length === 0) {
        container = jQuery('<ul class="live-search-results"></ul>');
        container.appendTo(element);
    }
    container.hide();
    noResults.hide();

    resetter = element.find(".reset");
    
    resetter.hide();

    // Stop the timer
    function stopTimer() {
        return timer && (timer = clearTimeout(timer));
    }

    /*
      The logic behind it all. This object is returned, so it can be manipulated in tests
    */
    publicApi = {
        
        // Receive a search, queue it for some time, then perform the search
        queueSearch: function(phrase) {
            if (phrase === "") {
                this.reset();
                return;
            }
            if (new RegExp("^" + previous + "$", "i").test(phrase)) {
                return;
            }
            stopTimer();
            previous = phrase;
            timer = setTimeout(function (){
                return this.performSearch(phrase);
            }.bind(this), options.delay);
        },

        // Actually call out to the backend and perform the search
        performSearch: function(phrase) {
            stopTimer();
            previous = phrase;
            element.addClass(options.waitingClass);
            var callback = this.populate.bind(this);
            backend.get(uri, phrase, callback);
        },

        // When we receive a result, populate this into the dom
        populate: function(result, phrase) {
            if (typeof result != "object")
                throw new TypeError("Expected an object");

            if (options.onDisplay)
                options.onDisplay();

            resetter.show();
            element.removeClass(options.waitingClass);
            container.html("").show();
            if (result.length < 1) {
                noResults.show();
            } else {
                noResults.hide();
                jQuery.each(result, function (i, obj) {
                    markup = options.renderer.render(obj);
                    markup.appendTo(container);
                });
            }
        },

        // Remove the search results, call into onReset 
        reset: function() {
            if (options.onReset)
                options.onReset();

            input.val("");
            resetter.hide();
            container.hide();
        }
    };

    // Hook into the events in the DOM
    (function (){
        var handler = function(e) {
            return publicApi.queueSearch(input.val());
        }
        
        var resetFunc = function(e) {
            return publicApi.reset();
        }
        input.keyup(handler);    
        input.focus(handler);
        resetter.click(resetFunc);
        element.submit(handler);
    })();

    return publicApi; // Return the API itself so we can play around with it

}