使用requireJS加载标准javascript文件

问题描述:

我正在尝试使用requireJS,以便使用Knockout改进ASP.NET MVC应用上Javascript的负载.

I'm trying out requireJS in order to improve the loading of Javascript on an ASP.NET MVC app, using Knockout.

我有一些定义自定义ko绑定的文件,

I have some files defining custom ko bindings like that:

(function (ko, bindings) {
    bindings.stopBinding = {
        init: function () {
            return { controlsDescendantBindings: false };
        }
    };

    bindings.anotherBinding = { ... };
})(ko, ko.bindingHandlers);

如果我尝试通过这种方式将其作为requireJS模块加载:

If I try to load it as a requireJS module this way:

define(['jquery', 'knockout', 'custom/knockout.bindings'], function ($, ko){
   ko.applyBindings(...);
});

我收到ko is not defined错误.

我知道我可以将该文件包含在require回调中,以便使它工作:

I know that I could enclose this file in a require callback for instance in order ot make it work:

require(['knockout'], function (ko) {
    (function (ko, bindings) {
        bindings.stopBinding = {
            init: function () {
                return { controlsDescendantBindings: false };
            }
        };

        bindings.anotherBinding = { ... };
    })(ko, ko.bindingHandlers);
});

是否有另一种方法可以使该文件工作而不必更新应用程序中的每个旧JS文件?我曾想过使用垫片,但是我什么也没得到,但是我对requireJS相当陌生,所以也许我缺少明显的东西.

Is there another way to allow this file to work without having to update each and every legacy JS file in the application ? I thought of using shim, but I didn't get anywhere, but I'm quite a noob with requireJS, so maybe I'm missing something obvious.

感谢此答案,我设法注入了淘汰出全局命名空间,使其可用于需要它的旧Javascript文件.

Thanks to this answer, I managed to inject Knockout back in the global namespace, making it available to legacy Javascript files that needed it.

首先,创建一个将ko注入到全局名称空间中的模块:

First, create a module that injects ko in the global namespace:

define('knockout.inject', ['knockout'], function (k) {
    window.ko = k;
    return k;
});

然后,将模块映射到基因敲除,以针对每个基因敲除依赖性执行该模块.

Then, map the module to knockout to execute it for every knockout dependency.

var require = {
    baseUrl: "/Scripts",
    paths: {
        //...
        "knockout": "knockout-3.3.0.debug",
        "knockoutbindings": "knockout.bindings",
    },
    shim: {
        "knockoutbindings": {
            deps: ["knockout"]
        }
    },
    map: {
        // inject ko back in the global namespace
        '*': {
            'knockout': 'knockout.inject'
        },
        // prevent cycles
        'knockout.inject': { 'knockout': 'knockout' }
    }
};