You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FullCalendar如何按已加载资源逐个请求接口获取日程事件?

最优实现方案

方案1:外部变量缓存资源列表

  • 逻辑:在日历实例外声明一个变量存储已加载的资源,资源请求成功后更新该变量,事件请求时直接读取
  • 优点:逻辑简单易维护,兼容性好
  • 代码示例:
// 外部缓存资源列表
let cachedResources = []
var timeline = new Calendar(timelineEl,{
  initialView: 'resourceTimeline',
  resources: function(fetchInfo, successCallback, failureCallback){
    // 发起ajax请求拉取资源
    fetch('/api/resources')
      .then(res => res.json())
      .then(resources => {
        cachedResources = resources // 加载成功后更新缓存
        successCallback(resources)
      })
      .catch(err => failureCallback(err))
  },
  events: async function(fetchInfo, successCallback, failureCallback){
    // 用Promise.all并发拉取所有资源对应的事件,提升性能
    const eventPromises = cachedResources.map(resource => {
      return fetch(`/api/events?resourceId=${resource.id}&start=${fetchInfo.startStr}&end=${fetchInfo.endStr}`)
        .then(res => res.json())
        .then(events => {
          // 自动关联resourceId,FullCalendar会自动识别绑定
          return events.map(event => ({...event, resourceId: resource.id}))
        })
    })
    try {
      const eventsList = await Promise.all(eventPromises)
      // 合并所有事件返回
      successCallback(eventsList.flat())
    } catch (err) {
      failureCallback(err)
    }
  }
})

方案2:调用FullCalendar内置API直接获取资源(更推荐)

  • 逻辑:FullCalendar实例本身提供getResources()方法,可以直接获取当前日历已加载完成的所有资源列表,不需要额外维护缓存变量
  • 优点:不需要额外维护缓存,避免缓存和实际加载资源不一致的问题,逻辑更干净
  • 代码示例:
var timeline = new Calendar(timelineEl,{
  initialView: 'resourceTimeline',
  resources: function(fetchInfo, successCallback, failureCallback){
    fetch('/api/resources')
      .then(res => res.json())
      .then(resources => successCallback(resources))
      .catch(err => failureCallback(err))
  },
  events: async function(fetchInfo, successCallback, failureCallback){
    // 直接调用实例方法获取当前已加载的所有资源
    const currentResources = timeline.getResources()
    const eventPromises = currentResources.map(resource => {
      // 注意这里resource是FullCalendar封装的对象,直接取resource.id即可
      return fetch(`/api/events?resourceId=${resource.id}&start=${fetchInfo.startStr}&end=${fetchInfo.endStr}`)
        .then(res => res.json())
        .then(events => events.map(event => ({...event, resourceId: resource.id})))
    })
    try {
      const eventsList = await Promise.all(eventPromises)
      successCallback(eventsList.flat())
    } catch (err) {
      failureCallback(err)
    }
  }
})

时序问题处理

默认情况下FullCalendar会并行发起资源和事件的请求,可能出现事件拉取时资源还未加载完成的问题,添加以下配置即可解决:

var timeline = new Calendar(timelineEl,{
  // 其他配置不变
  resourcesSet: function() {
    // 资源加载完成后手动触发事件刷新
    timeline.refetchEvents()
  }
})

内容的提问来源于stack exchange,提问作者Ilan_Schindler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:54:03