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.

2
  • you will want to shim them. Commented Mar 13, 2015 at 13:15
  • @DanielA.White I know, but I am kind of clueless about how to configure the shim in question. Commented Mar 13, 2015 at 13:17

1 Answer 1

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' }
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.