Load standard javascript files with requireJS

纵饮孤独 提交于 2019-12-12 02:14:32

问题


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

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

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

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

I get a ko is not defined error.

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

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.


回答1:


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

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


来源:https://stackoverflow.com/questions/29033187/load-standard-javascript-files-with-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!