【问题标题】:Using knockout.simpleGrid.3.0.js with Require.js将 knockout.simpleGrid.3.0.js 与 Require.js 一起使用
【发布时间】:2014-04-17 22:34:53
【问题描述】:
我在网站上使用带有敲除的 require.js,并希望使用此链接 http://knockoutjs.com/examples/grid.html 中的 simpleGrid 示例,但是我不能将 kncokout.simpleGrid.3.0.js 包含在 Require 中。
我已经尝试用
包装插件
define(['jQuery', 'knockout'], // Require knockout
function($, ko) {
});
这不起作用,模板似乎出现问题。
任何帮助表示赞赏
【问题讨论】:
标签:
javascript
knockout.js
requirejs
【解决方案1】:
在您的 require 配置中,您应该创建一个 simpleGrid 库的路径,并使用 shim 告诉它它依赖于 Knockout,以便您的库以正确的顺序加载。这是一个例子:
var require = {
paths: {
'jquery': 'lib/vendor/jquery-2.0.3',
'ko': 'lib/vendor/knockout-3.0.0',
'koSimpleGrid': 'lib/vendor/knockout.simpleGrid.3.0'
},
shim: {
'koSimpleGrid': {
deps: ['ko']
},
}
};
然后您可以从示例中复制粘贴视图模型代码,如下所示:
define(['jquery', 'ko', 'koSimpleGrid'], function ($, ko) {
// VIEW MODEL GOES HERE
});
【解决方案2】:
我同意问题似乎出在编写网格模板的代码上。本质上,因为 requirejs 异步加载模块,document.write() 无法使用 - 在模块执行时,文档的写入已经完成。 This StackOverflow answer explains it well 我想。
我通过 使用 dom 方法创建和附加所需的脚本标签模板来解决它:
templateEngine.addTemplate = function(templateName, templateMarkup) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/html';
scriptTag.id = templateName;
scriptTag.text = templateMarkup;
document.getElementsByTagName('body')[0].appendChild(scriptTag);
};
My amd version is in this gist.