【问题标题】:Aurelia - View render before custom element is ready/boundAurelia - 在自定义元素准备好/绑定之前查看渲染
【发布时间】:2017-05-16 22:33:22
【问题描述】:

我有一个非常简单的应用程序,只有一个视图和一个自定义元素。

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,但无法让它工作。不知道是不是和我一样。

回答 该链接实际上提供了正确的答案。我可以使用CompositionTransaction 让视图等待元素。我相信我有一些缓存文件,并且在更改代码时它在我删除浏览器(chrome)中的缓存之前不起作用。

【问题讨论】:

  • 看起来该示例中的关键是使用this.compositionTransactionNotifier = this.compositionTransaction.enlist();this.compositionTransactionNotifier.done();。虽然这对你不起作用?
  • 不,它没有。但我只是做了一个快速测试。我可能有什么问题。我会再试一次,看看我是否是一个可能的解决方案。
  • 当然可以。好像我有一些缓存文件在我更改代码后导致了一些问题。
  • 可能值得用你的最终工作代码@John 自行回答这个问题 - 我认为这将是一个非常常见的问题,

标签: aurelia


【解决方案1】:

答案确实是在上述情况下使用CompositionTransaction。 这个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();
        });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2015-08-07
    • 2016-10-06
    • 1970-01-01
    • 2020-03-28
    • 2012-12-26
    • 2015-12-02
    相关资源
    最近更新 更多