首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FastBoot SimpleDOM车身是空的

FastBoot SimpleDOM车身是空的
EN

Stack Overflow用户
提问于 2017-03-19 22:22:25
回答 1查看 227关注 0票数 0

我试图在FastBoot环境中的实例初始化器中读取DOM,但document.body似乎是空的。以下代码在浏览器中工作,但在FastBoot中不返回任何内容:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
/* 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>
    `;
  }
};
EN

回答 1

Stack Overflow用户

发布于 2017-03-19 23:19:41

在应用程序引导生命周期中,document.body始终是空的。由于呈现尚未完成(在实例初始化阶段),因此没有替换快速引导占位符。

您可以执行以下任何一项操作:

  1. 您可以使用shoebox来推送和获取快速引导引导数据:http://ember-fastboot.com/docs/user-guide#the-shoebox
  2. 如果您想要在应用程序生命周期之外完成它,那么您可以在完成fastboot.visit请求之后和在调用result.html()之后完成它。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42893019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档