【问题标题】:Why cannot modify a value of an object in a CommonJS module?为什么不能修改 CommonJS 模块中对象的值?
【发布时间】:2017-02-02 07:36:30
【问题描述】:

我有这个基本的koa v2 应用程序,我在其中尝试将模板文字实现为查看引擎。在./views/index.js 中,如何从app.js 填充state 的值?

我的问题是我想将对象值从ctx.body = index.render({}) 一直推送到.views/partials/mainTop.js 文件,假设我想在<title></title> 标签之间包含title 对象值。有没有办法在app.js 中不需要.views/partials/mainTop.js 来实现这一点?如果它是把手或 nunjucks 模板,我想用模板文字实现类似的事情。

./app.js

const index = require('./views/index');
const app = new Koa();

app.use(ctx => {
  index.state = {
    foo: 'bar',
  };
  ctx.body = index.render({
    title: 'Template Literals',
    description: 'Vanilla JS rendering',
  });
});

app.listen(3000);

./views/index.js

const main = require('./layouts/main');

let state = {};
module.exports.state = state;
console.log(state); // returning an {} empty object, expected => { foo: "bar" }

module.exports.render = (obj) => {
  return main.render(`
    <p>Hello world! This is HTML5 Boilerplate.</p>
    ${JSON.stringify(obj, null, 4)}}
    ${obj.title}
  `);
};

./views/layouts/main.js

const mainTop = require('../partials/mainTop');
const mainBottom = require('../partials/mainBottom');

module.exports.render = (content) => {
  return `
    ${mainTop.render}

    ${content}

    ${mainBottom()}
  `;
}

./views/partials/mainTop.js

const render = `
  <!doctype html>
  <html class="no-js" lang="">
  <head>
  <title></title>
  ...
`;
module.exports.render = render;

./views/partials/mainBottom.js

module.exports = () => {
  return `
    ...
    </body>
    </html>
  `;
}

【问题讨论】:

  • 不清楚。你可以定义一个任何地方都可以访问的方法来返回值,或者最后的手段,使用一个全局的。
  • 我想知道为什么mainTop被定义为具有字符串属性的对象,而mainBottom被定义为返回字符串的函数。

标签: javascript node.js commonjs es6-modules template-literals


【解决方案1】:

console.log(state); // 返回一个 {} 空对象,预期 => { foo: "bar" }

当然你得到的是你刚刚创建的空对象:

  • 这是在 app.js 中分配给的 module.exports.state 属性。您的本地 state 变量不会被覆盖,它所指的对象也不会发生突变。为此,您需要在 index.js 中执行 index.state.foo = "bar";
  • 对象/变量在创建为空对象后立即被记录。 index.js 中的赋值是异步发生的,在 app.use 回调中。如果您在 render 方法中执行了console.log,该方法在赋值之后 被调用,那么您将得到预期的值。但是,在这种情况下,您可能应该将其作为参数传递。

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多