jQuery自动完成:如何启用缓存?

时间:2012-07-12 05:17:26

标签: jquery-ui autocomplete

这是我使用函数推送建议数组的源代码:

jQuery(document).ready(function ($){
    var cache = {};
    function split( val ) {
        return val.split( /,\s*/ );
    }

    function extractLast( term ) {
        return split( term ).pop();
    }

    $("#ctags-input")
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })

    .autocomplete({ 

        source: function(req, add){
            var ctags_action = 'suggest_tags';

            var term = req.term;
            if (term in cache) {
               add(cache[term]);
               return;
            }

    $.getJSON(SuggestTags.url+'?callback=?&action='+ctags_action, req, function(data) {
                var suggestions = [];
                $.each(data, function(i, val){                              
                    suggestions.push({
                        label: val.name,
                        count: val.count
                    });
                });
                cache[term] = suggestions;  
                add(suggestions);

            });
        },          
        focus: function() {
            return false;
        },

        select: function( event, ui ) {
            var terms = split( this.value );
            terms.pop();
            terms.push( ui.item.value );
            terms.push( "" );
            this.value = terms.join( ", " );
            return false;
        }   
    })

    .data( "autocomplete" )._renderItem = function( ul, item ) {        
        return $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.label + " (" + item.count+ ")</a>")        
        .appendTo(ul);
    };      
});

要添加缓存能力,jQ UI网站演示直接使用数据响应:

source: function( request, response ) {
   var term = request.term;
    if ( term in cache ) {
      response( cache[ term ] );
      return;
    }

   lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
    cache[ term ] = data;
    if ( xhr === lastXhr ) {
        response( data );
    }
 });
}

如何在我的代码中实现此缓存演示?

1 个答案:

答案 0 :(得分:1)

suggestions放入缓存中。

var term = req.term;
if (term in cache) {
   add(cache[term]);
   return;
}
...
cache[term] = suggestions;
add(suggestions);