twitter typeahead + bloodhound reutilization:如何显示ajax请求的加载gif?

时间:2014-06-02 00:34:50

标签: loading typeahead.js twitter-typeahead bloodhound

我的猎犬对象被两个类型的对象重复使用,每个类型的对象都有一个隐藏的图像,这两个图像是#loading-1#loading-2

    galleriesBloodhound = new Bloodhound({
        datumTokenizer: function (gallery) { return gallery.name; },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: '/GalleriesAjax/List?nameQuery=%QUERY',
            beforeSend: function (xhr) {

            },
            filter: function (response) {
                return response.pageOfGalleries;
            }
        }
    });

Typeahead#1:

    $("#gallery-name").typeahead({
        highlight: false,
        hint: true,
    },
    {
        name: 'galleries',
        displayKey: function (gallery) { return gallery.displayName; },
        source: galleriesBloodhound.ttAdapter()
    }).on(..).on(..)...

Typeahead#2(相同代码)

    $("#gallery2-name").typeahead({
        highlight: false,
        hint: true,
    },
    {
        name: 'galleries',
        displayKey: function (gallery) { return gallery.displayName; },
        source: galleriesBloodhound.ttAdapter()
    }).on(..).on(..)...

如果ajax请求尚未返回,如何显示正确的#loading-1#loading-2

在typeahead.js的网站上,他们建议使用beforeSendfilter,但“从那里”我怎么知道哪个类型是召唤猎犬的那个?

    beforeSend: function (xhr) {
         $("#loading-i").show();     // How do I figure "i" ??
    },
    filter: function (response) {
        $("#loading-i").hide();     // How do I figure "i" ??
        return response.pageOfGalleries;
    }

    // i depends on the typeahead that is using "this" bloodhound

3 个答案:

答案 0 :(得分:3)

好吧,我解决了我们的问题(尽管我对此并不是100%满意!),但有以下假设:焦点元素应始终是typeahead附加文本字段< /强>

这是代码(Bloodhound对象初始化):

var locsData = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: "/locations/search.json?q=%QUERY",
    ajax: {
      beforeSend: function(xhr, settings) {
        // maybe the 'if' is not necessary, but just to be sure...
        if ($(document.activeElement).typeahead != null) {
          $(document.activeElement).addClass('loading-text');
        }
      },
      complete: function(xhr, status) {
        if ($(document.activeElement).typeahead != null) {
          $(document.activeElement).removeClass('loading-text');
        }
      }
    }
  },
  limit: 100
});

在你的情况下,你正在切换某个元素的显示(<span>?),在我的项目中,我正在为元素添加/删除一个类(这样的类在里面显示loading.gif文本字段的右边距),但想法应该是相同的。

现在我将在我的项目中使用它。我希望这对你也有用。

答案 1 :(得分:1)

答案 2 :(得分:0)

当然,您可以使用最近的 .next JQuery函数来找到所需的元素。