我最終用自己的電話從服務器端獲取文件。
在節點(但可以用PHP來完成或任何其他語言也一樣),我添加了一個途徑來獲取所需的文件:
router.get('/loadFile/', function(req, res, next){
var params = req.query;
var demo = express.static(path.join(res.locals.virtualDirPath, 'public'));
fs.readFile(__dirname + '/../public/elements/' + params.filename, "utf-8", function read(err, data) {
if (err) {
throw err;
}
// Invoke the next step here however you like
return res.send(data);
processFile();
});
});
然後,我創建了自己的自定義組件加載器中的JavaScript方面詳述如下in the docs。
var templateFromUrlLoader = {
loadTemplate: function(name, templateConfig, callback) {
var newUrl = url + 'others/loadFile/';
var params = { 'filename' : templateConfig.filename };
if (templateConfig.filename) {
// Uses jQuery's ajax facility to load the markup from a file
$.get(newUrl, params, function(markupString) {
// We need an array of DOM nodes, not a string.
// We can use the default loader to convert to the
// required format.
ko.components.defaultLoader.loadTemplate(name, markupString, callback);
});
} else {
// Unrecognized config format. Let another loader handle it.
callback(null);
}
}
};
// Registering it
ko.components.loaders.unshift(templateFromUrlLoader);
這樣我就不必爲這個簡單的任務加載84Kb的require.js。 Plus I'm not limited通過這種方式使用require.js,我可以在生產環境中使用單個組合文件和縮小文件。
另外,我完全控制了返回的模板的緩存,這在使用require.js時會導致我的問題。
你看過這個文檔頁嗎? http://knockoutjs.com/documentation/component-loaders.html#custom-component-loader在我看來,你將不得不實施'loadTemplate'方法來從服務器獲取html ... – user3297291
這是一個文章,我寫了一段時間的一些選項:https://www.safaribooksonline.com/blog/2014/01/31/using-external-templates-knockout-js/。使用基於字符串的模板引擎和構建步驟捆綁您的模板是我過去使用的一種可能的選擇。 –