【问题标题】:javascript modules export updated variablejavascript 模块导出更新的变量
【发布时间】:2018-12-21 15:07:01
【问题描述】:

我是 js 模块的新手,我不完全理解它们是如何工作的,我的问题是;

我在更多模块中需要这个 fixed var,所以目前我的代码是:

let fixed

const getFixed = () => {
  return $.getJSON('data/fixed.json')
    .done((data) => {
      fixed = data.settings[0]
    })
    .fail((jqxhr, textStatus, error) => {
      const err = `${textStatus} , ${error}`
      alert(`fixed.json for getSettings Request Failed: ${err}`)
    })
}

const init = () => {
  return getFixed()
}

const getFixedSettings = () => {
  return fixed
}

export default {
  init,
  getFixedSettings
}

在我的应用程序中,它是另一个模块,我这样做:

import functions from './functions'

const initialize = () => {
  // update the settings
  functions.init()
// initialize the map
.then(() => mapInit(functions.getFixedSettings()))
}

但是当我在另一个模块中请求 functions.getFixedSettings() 时,我需要再次调用 functions.init() 才能获得更新的 var

导出更新的fixed var 并可供我的所有模块访问的正确方法是什么?

【问题讨论】:

    标签: javascript webpack es6-modules


    【解决方案1】:

    如果您希望 fixed 可以被所有模块访问,您可以只导出 fixed: export let fixed

    【讨论】:

    • 是的,但正如您所见,fixed 是在 ajax 请求之后填充的,这是我的问题
    • 你的意思是你想让固定的变量填充一次然后在任何地方使用它?
    • 是的,因为目前我需要调用functions.init() 然后我可以使用functions.getFixedSettings() 我的代码现在实际上正在运行,但是在每个模块中我需要运行functions.init() 然后我可以使用functions.getFixedSettings()
    • 编写一个通用类,他的角色是执行一次functions.init(),而不是将结果存储在代码中任何地方都可以访问的属性中。
    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2020-12-26
    相关资源
    最近更新 更多