jQuery的自动完成:如何启用缓存? [英] jQuery Autocomplete: How to enable cache?

查看:185
本文介绍了jQuery的自动完成:如何启用缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的源$ C ​​$ C使用功能来推动的建议数组:

This is my source code that use a function to push the suggestion array:

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网站演示直接用于数据回应:

To add cache ability, jQ UI site demo directly uses response for data:

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

如何实现我的code这个缓存演示?

How to implement this cache demo in my code?

推荐答案

建议在缓存中。

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

这篇关于jQuery的自动完成:如何启用缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆