0

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.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85

1 Answers1

0

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' }
    }
};
Community
  • 1
  • 1
xlecoustillier
  • 16,183
  • 14
  • 60
  • 85