如何防止多次ajax查询在多次单击“prev”按钮上运行

时间:2016-05-15 09:15:22

标签: javascript jquery fullcalendar

默认情况下,我的日历在“agendaWeek”视图中。 我正在使用“事件(作为一个函数)”来获取动态事件数据。

为了快速到达我想查看的一周,我快速点击“prev”多次。界面快速赶上,但每次单击都会触发ajax请求。这并不理想,因为它会缩短所需周的响应时间,因为必须处理每个干预周的ajax请求。

如何减轻这种情况?我的想法是,这确实是一个功能请求。在执行“事件”功能之前,库应该等待300毫秒。

4 个答案:

答案 0 :(得分:1)

听起来你需要去掉ajaxing函数:

  

The Debounce technique allow us to "group" multiple sequential calls in a single one.

Here's最新的lodash实现,这是我使用的。

答案 1 :(得分:0)

O(log(n)M(n))

O(M(n))

类似的......

答案 2 :(得分:0)

我能够通过使用eventSources并返回一个函数数组来使debounce工作,每个事件源都有一个函数。 getSources功能仅仅是为了方便起见。在fullCalendar配置中,我们将:

...
eventSources: getSources(),
...

功能代码:

let source1Params = {};
let source2Params = {};

let debouncedSource1 = debounce(
  function () {
    $.ajax( {
      url: 'source/1/feed',
      dataType: 'json',
      data: {
        start: source1Params.start,
        end: source1Params.end
      },
      success: function( response ) {
        // Parse the response into an event list
        let eventList = ...
        source1Params.callback( eventList );
      }
    } );
  }, 200
);

let debouncedSource2 = debounce(
  function () {
    $.ajax( {
      url: 'source/2/feed',
      dataType: 'json',
      data: {
        start: source2Params.start,
        end: source2Params.end
      },
      success: function( response ) {
        // Parse the response into an event list
        let eventList = ...
        source2Params.callback( eventList );
      }
    } );
  }, 200
);

function getSources() {
  return [
    {
      id: 'source1',
      events: ( start, end, timezone, callback ) => {
        source1Params = {
          'start': start,
          'end': end,
          'timezone': timezone,
          'callback': callback
        };
        debouncedSource1();
      }
    },
    {
      id: 'source2',
      events: ( start, end, timezone, callback ) => {
        source2Params = {
          'start': start,
          'end': end,
          'timezone': timezone,
          'callback': callback
        };
        debouncedPlanned();
      }
    }
  ];
}

这部分工作,即如果你连续点击下一个或上一个按钮,它将阻止多个请求,只根据需要发送最后一个请求。然而,这也有多个警告:

  • 配置中的loading回调将不再有效。这是因为loadingLevel在内部实现的方式,它会通过快速点击而增加,但不会减少,因此永远不会达到零,从而触发回调。
  • 单击下一步,等待去抖定时器结束并启动加载,然后在加载时再次单击下一步将导致不可预测的结果,而不会呈现事件。我现在的解决方案是在加载事件时禁用导航按钮。这解决了问题,但导致导航响应性降低。

答案 3 :(得分:-1)

用户可观察它会帮助您解决问题 observable

也阅读了这篇文章 http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

这段代码来自上面的链接,它的真实角度,但你可以在任何地方使用observables。

constructor(private wikipediaService: WikipediaService) {
    this.term.valueChanges
             .debounceTime(400)
             .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
  }
相关问题