2017-05-05 88 views
1

我有一個非常簡單的應用程序,只有一個視圖和一個自定義元素。Aurelia - 在自定義元素準備好/綁定之前查看渲染

app.html:

<template> 
    <require from="./content"></require> 
    hello 
    <content></content> 
</template> 

content.html:

<template> 
    ${message} 
</template> 

content.js:

import {HttpClient} from 'aurelia-http-client'; 
import {inject} from 'aurelia-framework'; 

@inject(HttpClient) 
export class Content { 

    constructor(http) { 
    this.http = http; 
    } 

    bind() { 
     return this.http.get('https://api.github.com/users/aurelia/repos') 
     .then(c => this.message = 'world'); 
    } 
} 

裏面的綁定生命週期事件我有一個REST服務調用(帶有承諾),它提取了一些數據。我在這裏遇到的問題是,如果這個異步調用需要一些時間,app.html將在之前渲染,然後當數據被提取時,它將被綁定到元素。我的意思是,首先瀏覽器呈現Hello,然後在一段時間後呈現world。我不喜歡我正在處理的特定網站上的這種行爲。相反,我更喜歡瀏覽器是空白的,並在一切準備就緒時渲染所有內容。 就像我正在處理服務器端渲染一樣。然後,瀏覽器正在等待服務器在獲取它之前構建完整的響應,然後將其呈現。

事件activate()在視圖模型中工作,但現在我有一個自定義元素。是否有可能做類似的事情? 我需要獲取不在視圖模型中的自定義元素中的數據。否則,我知道我可以在視圖模型中獲取它,然後通過屬性將其綁定到元素。這對我來說是不可能的。 另外,我看着這個link,但不能得到它的工作。不知道是否和我一樣。

答案 鏈接確實提供了正確的答案。我可以使用​​讓視圖等待元素。我相信我有一些緩存文件,並且在我刪除瀏覽器中的緩存(chrome)之前,更改代碼時它不起作用。

+0

看起來像在示例的關鍵是使用'this.compositionTransactionNotifier = this.compositionTransaction.enlist(); '和'this.compositionTransactionNotifier.done();'。雖然這不適合你? – Tom

+0

不,它沒有。但我只做了一個快速測試。我可能有錯誤。我會再試一次,看看我是否有可能的解決方案。 – John

+1

當然,它的工作原理。似乎我有一些緩存文件,導致我在更改代碼後出現了一些問題。 – John

回答

0

答案的確是在上面的情況下使用​​。 這個link顯示了一個例子。 在我的例子的解決方案是改變視圖模型content.js到這樣的事情:

import {HttpClient} from 'aurelia-http-client'; 
import {inject, CompositionTransaction } from 'aurelia-framework'; 

@inject(HttpClient, CompositionTransaction) 
export class Content { 

    constructor(http, compositionTransaction) { 
    this.http = http; 
    this.compositionTransactionNotifier = compositionTransaction.enlist(); 
    } 

    bind() { 
     return this.http.get('https://api.github.com/users/aurelia/repos') 
     .then(c => { 
      this.message = 'world'; 
      this.compositionTransactionNotifier.done(); 
     }); 
    } 
}