使用define 或者 require 加载knockout.mapping 时找不到fromJS问题解决

问题:

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'}
    }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值