0

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

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 );
    }
 });
}

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

4

1 回答 1

1

放入suggestions缓存。

var term = req.term;
if (term in cache) {
   add(cache[term]);
   return;
}
...
cache[term] = suggestions;
add(suggestions);
于 2012-07-12T05:39:27.257 回答