【问题标题】:How to refresh bootstrap-select's options after load data from ajax api从ajax api加载数据后如何刷新bootstrap-select的选项
【发布时间】:2017-09-15 21:33:56
【问题描述】:

我已经创建了 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>

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

我觉得不好,但我没有更好的方法来解决它, 我知道许多 jQuery 插件应该使用完整的 dom 元素并渲染它们,但是在 aurelia 框架 attach() 方法中,一些数据从异步 api 加载 在异步数据绑定到 dom 后是否有一些后处理方法或事件可以调用

【问题讨论】:

    标签: aurelia bootstrap-select


    【解决方案1】:

    您可以对微任务进行排队,确保您的函数在更新 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");
        });
      }
    }
    

    类似问题:@bindable changeHandler fires before bindings are done updating

    希望这会有所帮助!

    【讨论】:

    • 感谢您的帮助,经过一些测试,我发现这不起作用,但我使用 this.taskQueue.queueTask 获得与我想要的相同的效果,阅读文章ilikekillnerds.com/2016/02/working-with-the-aurelia-task-queue我只是知道queueMicroTask在queueTask之前运行,我在我的项目中测试了很多情况,使用queueMicroTask时有些工作有些没有,关于这两种方法是否有更多细节。非常感谢
    • 答案应该有效...可能还有其他因素影响您的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2018-11-20
    • 2012-10-11
    • 2012-08-14
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多