我试图在FastBoot环境中的实例初始化器中读取DOM,但document.body似乎是空的。以下代码在浏览器中工作,但在FastBoot中不返回任何内容:
const ELEMENT_NODE_TYPE = 1;
// TODO(maros): Get this working with FastBoot. For some reason the SimpleDOM
// body is empty.
const findBootstrapData = (document) => {
for (let currentNode = document.body.firstChild; currentNode; currentNode = currentNode.nextSibling) {
if (currentNode.nodeType !== ELEMENT_NODE_TYPE) {
continue;
}
if (currentNode.getAttribute('class') === 'bootstrap-data') {
return JSON.parse(currentNode.firstChild.nodeValue);
}
}
};
export function initialize(appInstance) {
const store = appInstance.lookup('service:store');
const document = appInstance.lookup('service:-document');
const data = findBootstrapData(document);
if (data) {
store.push({ data: data.posts });
}
}
export default {
name: 'blog-posts',
initialize
};我试图读取的数据已经使用Ember插件注入到{{content-for "body"}}部分。在没有FastBoot的情况下,这是非常有效的。
如何让这个实例初始化器在FastBoot中工作?
编辑:
对于额外的上下文,下面是我如何使用Ember CLI插件填充DOM:
/* eslint-env node */
'use strict';
const fs = require('fs');
const path = require('path');
const convertMarkdown = require('marked');
const parseFrontMatter = require('front-matter');
// Reads blog posts from `/posts`, compiles from markdown to HTML and stores
// as JSON in a script tag in the document. An instance initializer then picks
// it up and hydrates the store with it.
module.exports = {
name: 'blog-posts',
contentFor: function(type) {
if (type !== 'body') {
return;
}
const dirname = path.join(__dirname, '..', '..', 'posts');
const data = fs.readdirSync(dirname).map((filename, index) => {
if (!filename.endsWith('.md')) {
return;
}
const fileContent = fs.readFileSync(path.join(dirname, filename), 'utf-8');
const frontMatter = parseFrontMatter(fileContent);
return {
id: index + 1,
type: 'post',
attributes: {
title: frontMatter.attributes.title,
body: convertMarkdown(frontMatter.body),
},
};
});
return `
<script class="bootstrap-data" type="text/template">
${JSON.stringify({ posts: data })}
</script>
`;
}
};发布于 2017-03-19 23:19:41
在应用程序引导生命周期中,document.body始终是空的。由于呈现尚未完成(在实例初始化阶段),因此没有替换快速引导占位符。
您可以执行以下任何一项操作:
fastboot.visit请求之后和在调用result.html()之后完成它。https://stackoverflow.com/questions/42893019
复制相似问题