如何在从 ajax api 加载数据后刷新 bootstrap-select 的选项

How to refresh bootstrap-select's options after load data from ajax api

我创建了 aurelia 自定义属性代码如下

@customAttribute('bt-select')
@inject(Element)
export class BootstrapSelect {
  @bindable val;
  @bindable list;

  constructor(element) {
    this.element = element;

  }

  attached() {
    $(this.element).selectpicker();
  }

  valChanged(newValue, oldValue) {
      $(this.element).selectpicker("val",_.isObject(newValue)?newValue.id:newValue);
  }

  listChanged(newValue, oldValue) {
    setTimeout(()=>{
       $(this.element).selectpicker("refresh");
    },300)
  }

  detached(){
    this.val = null;
    this.list = null;
    $(this.element).selectpicker("destroy");
  }

}

并按如下方式使用它

<select value.bind="form.category" data-width="100"
                                bt-select="val.bind:form.category;list.bind:categorys;">
                          <option value="">select:category</option>
                          <option repeat.for="category of categorys"
                                  value="${category.id}">
                            ${category.name}
                          </option>
                        </select>

select 的选项标签从 class 道具类别中重复,this.categorys 来自 ajax api 的 loda 数据,这是渲染 select选项标签 我必须在 listChanged 方法中添加 setTimeout func 以等待 aurelia 渲染 select 的选项标签完成,然后强制刷新 bootstrap-select 组件

感觉不太好,但是没有更好的办法解决, 我知道很多 jQuery 插件应该使用完成的 dom 元素并渲染它们,但是在 aurelia 框架附加()方法中,一些数据从异步加载 api 在异步数据绑定到 dom

之后,是否有一些 post 处理方法或事件可以调用

您可以对微任务进行排队,确保您的函数在更新 DOM 后 运行。例如:

//...
import { TaskQueue } from 'aurelia-task-queue';

@inject(Element, TaskQueue)
export class BootstrapSelect {
  //...
  constructor(element, taskQueue) {
    this.element = element;
    this.taskQueue = taskQueue;
  }

  listChanged(newValue, oldValue) {
    // at this point, a micro-task for updating the dom is already queued.
    // now, you should queue a new task that will run after the previous one is completed. 
    this.taskQueue.queueMicroTask(() => {
      $(this.element).selectpicker("refresh");
    });
  }
}

类似问题:

希望对您有所帮助!