需要JS文本插件动态参数问题



我正在尝试编写一个可以用来拉动模板及其文本插件的功能。

我希望能够调用template('modules', 'login');并加载所需的模板。

define(function(require) {
    return function(path, file) {
        return require('lib/text!templates/ + path + '/' + file + '.html');
    }
});

因此,我的代码会引发错误,但是如果我用像这样的路径进行硬编码

require(lib/text!templates/modules/login.html)

它按照我想要的方式工作。我尝试使用来自函数的参数来创建字符串参数的不同变体,以使用混合结果并记录通过的字符串,以确保它们是相同的。有什么想法吗?

这是我回来的错误 Uncaught Error: Module name "lib/text!templates/modules/profile.html" has not been loaded yet for context: _

您可以做您想做的事,但不能使用 synchronous 函数。

当您将require(...)与单个参数(字符串)一起使用时,您正在依靠requirejs对CommonJS要求模块的支持。假设您在require(...)呼叫中放了一个字符串,您说的是有效的:

define(function(require) {
    return function(path, file) {
        return require('lib/text!templates/modules/login.html');
    }
});

幕后,requirejs将上述代码转换为类似的东西:

define(['require', 'lib/text!templates/modules/login.html'], function(require) {
    return function(path, file) {
        return require('lib/text!templates/modules/login.html');
    }
});

请注意define调用的附加依赖关系。到require执行时,您需要的模块已经加载,一切都很好。您作为模块值 can 同步返回'lib/text!templates/modules/login.html'的值时返回的函数。

问题在于,如果require(...)调用包含除字符串文字之外,此过程将无法工作。如果设置var x = 'lib/text!templates/modules/login.html',然后执行require(x)它将无法使用! requirejs将无法像我上面显示的那样执行转换,以及当require(...)执行时,它想要加载的模块尚未加载,并且失败。这只是启用J的限制。require(...)的形式具有字符串为唯一参数(而不是模块和回调列表)的形式仅存在以支持加载模块的commonjs方式。但是,如果尚未加载所需的模块,则require 的这种形式失败。这就是为什么requirejs会改变出现这种调用的模块,以便将模块要求的模块添加到模块依赖项列表中。但是,对于具有单个字符串字符字的单个参数的require(...)调用,它可以执行此转换。别无其他。

您的 can 做是:

define(function(require) {
    return function(path, file, cb) {
        require(['lib/text!templates/' + path + '/' + file + '.html'], cb);
    }
});

模块返回的值是 asynchronous 函数,该函数将其称为带有模板值的cb的回调。

最新更新