我正在尝试延迟加载木偶项目视图的模板,但事情没有按照我预期的方式工作。在遵循有关如何重写 getTemplate 方法的一些提示之后,我执行以下操作:
getTemplate: function () {
var template = require(['text!templates/login/loginbox-template.html'], function (template) {
return template;
});
return _.template(template);
}
但输出是 require 方法的函数体。
function localRequire(deps, callback, errback) (... and so on)
并且返回require方法也不起作用:
getTemplate: function () {
return require(['text!templates/login/loginbox-template.html'], function (template) {
return _.template(template);
});
}
这在控制台中给了我一些错误:
Uncaught RangeError: Maximum call stack size exceeded jquery-1.11.js?v=1393591915026:5801
Uncaught TypeError: Object #<Object> has no method 'slice'
似乎在require
完成之前返回了getTemplate
方法。我可以将返回包装在 setTimeout
函数中,但到目前为止这不是一个好的解决方案。
关于如何处理这个问题的任何想法?
当require()
用于延迟加载内容时,它是异步的。返回值无关紧要。您需要的是:
getTemplate: function () {
var template;
require(['text!templates/login/loginbox-template.html'], function (t) {
template = t;
// signal the application that template is resolved; I suggest promises
});
}
异步意味着执行结果不会立即可用。注释signal the application...
是代码的占位符,它将通知应用程序的其他部分结果实际可用,并且可以继续处理。如果您没有预料到,这很乏味,但事情就是这样。
看看 JS Promise API,它由许多伟大的库实现,从 jQuery 到独立的 Q 库。