2017-09-15 26 views
1

我已創建奧裏利亞自定義負載數據後,屬性代碼如下如何刷新自舉選的選項從AJAX API

@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 loda ajax api數據,它是異步步驟呈現選擇選項標記 ,我必須添加setTimeout func listChanged方法等待aurelia呈現select的選項標記com然後強制刷新引導選擇組件

我覺得它不好,但我沒有更好的方法來解決它,我知道許多jQuery插件應該使用完成的DOM元素並呈現它們,但在aurelia框架中附加()方法,異步api的一些數據加載 是否有一些後處理方法或異步數據綁定到dom後要調用的事件

回答

0

您可以排隊一個微任務,確保您的函數將在更新後運行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

希望這有助於!

+0

thx爲您的幫助,經過一些測試後,我發現這不起作用,但我使用this.taskQueue.queueTask獲得與我想要的相同的效果,閱讀文章後https://ilikekillnerds.com/2016/ 02/working-with-the-aurelia-task-queue /我只知道queueMicroTask在queueTask之前運行,而且我在我的項目中測試過很多情況,有些工作,有些不在使用queueMicroTask時,是否還有一些關於這些細節的更多細節兩種方法。 thx非常多 – date13

+0

答案應該有效......可能還有其他影響你的代碼的東西 –

相關問題