简体   繁体   English

RequireJS-返回延迟加载静态文件的内容

[英]RequireJS - Return content of lazy load static file

I am writing an util module, which contains a function that lazy load a json file and return the content, but I can't seem to get this working... 我正在编写一个util模块,其中包含一个懒加载json文件并返回内容的函数,但是我似乎无法正常工作...

define([
  'require'
], function (require) {
  var util = {
    jsonData: [],

    getJsonData: function () {
      require(['require', 'text!dummyData.json'], _.bind(function (require) {
        this.jsonData.concat(JSON.parse(require('text!dummyData.json')));
      }, this));
      return this.jsonData;
    }
  };
  return util;
});

Any idea what I am doing wrong ? 知道我在做什么错吗?

It is not working because you are trying (and failing) to return something from an asynchronous function. 它不起作用,因为您正在尝试(并且失败)从异步函数return某些内容。 All calls to require that have a list of dependencies as the first argument are asynchronous. 具有第一个自变量的依赖项列表的所有require调用都是异步的。 If you call require like this in a function of yours and your function is meant to provide back results that depend on this require call, then your function is also asynchronous. 如果您在自己的函数中这样调用require ,并且您的函数要提供依赖于此require调用的返回结果,则您的函数也是异步的。

You need something like the following code where getJsonData accepts a callback and calls it once it has the data. 您需要类似以下代码的内容,其中getJsonData接受回调,并在有数据后调用它。 I've also changed require('text!text!dummyData.json') to remove one of the text! 我还更改了require('text!text!dummyData.json')以删除其中一个text! prefixes, which has no business there. 前缀,那里没有业务。

define([
  'require'
], function (require) {
  var util = {
    jsonData: [],

    getJsonData: function (callback) {
      require(['require', 'text!dummyData.json'], _.bind(function (require) {
        this.jsonData.concat(JSON.parse(require('text!dummyData.json')));
        callback(this.jsonData);
      }, this));
    }
  };
  return util;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM