问题:
define(['knockout', 'knockout.mapping'], function(ko, mapping) { }
当使用ko.mapping.fromJS/时总是报fromjS无效方法。
原因是:
It sounds like Script# is assuming that ko
and ko.mapping
are in the global namespace, not loaded as AMD. BUT, Knockout and Knockout.mapping are coded such that when they detect AMD/RequireJS, they do not use the global namespace.
大概是说ko和ko.mapping在模块化加载时在同一全局命名空间里,这样会导致ko.mapping不能正确从“ko.mapping”模块引用。
解决方法:
require(["knockout", "knockout.mapping"], function (ko, m) { ko.mapping = m; })
或者
在上个例子中直接使用 m 作为 “ko.mapping", 如: m.fromJS(...)
还有一个解决办法:
- create your own wrapper module to inject it back into global. Something like this:
define('knockout.inject', ['knockout'], function(k)
{
window.ko = k; // make a ko global
return k; // but also return what a normal AMD require expects
});
define('knockout.mapping.inject', ['knockout.mapping'], function(m)
{
window.ko.mapping = m; // make a ko.mapping global
return m; // but also return what a normal AMD require expects
});
THEN, you can make a RequireJS map configuration so that whenever you request 'knockout' or 'knockout.mapping', they get transparently remapped to your above wrappers.
requirejs.config({
paths: { // same as original },
shim: { // same as original },
map: {
'*': {
'knockout': 'knockout.inject',
'knockout.mapping': 'knockout.mapping.inject'
},
// prevent cycles
'knockout.inject': {'knockout': 'knockout'},
'knockout.mapping.inject': {'knockout.mapping': 'knockout.mapping'}
}
});