0

I stumbled upon this post with a possible solution but it's not working and I am getting the same error ko is not define.

I placed this in a it's own JS file as I am assuming knockout.inject needs to be in a module as explained in the original post.

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

Then this:

require.config({

    paths: {
         knockout: 'Path to knockout',
        // This is the file
         knockoutbindings: 'knockout.bindings.orderable'
    },

    shim: {

        "knockoutbindings": {
            deps: ["knockout"]
        },
        map: {
            // inject ko back in the global namespace
            '*': {
                'knockout': 'knockout.inject'
            },
            // prevent cycles
            'knockout.inject': { 'knockout': 'knockout' }
        }
    }
});

However, I am not sure how to instantiate the file and I get the error: ko is undefined. Followed by the name of the file and directory.

With knockout mapping, all I had to do was:

ko.mapping = komapping;

How do I instantiate this file?

Community
  • 1
  • 1
Asynchronous
  • 3,917
  • 19
  • 62
  • 96

1 Answers1

0

If you load ko using require, directly, or as a dependency, ko isn't defined as a global variable, thus, it's not available for your not AMD plugins to attach to ko.

There are two solutions:

  1. Modify your plugins sothat they are amd compliant. That means loading ko as a dependency of your module, and include the plugin functionatility on the local reference to ko in your module

  2. Use shims, which is the not the best solution, but it's the easier one if you don't want to redefine your plugins as AMD compliant modules.

But please, don't mix both patterns, because you'll end add having local versions of ko which differ from the global version.

You can find an extensive explanation on how to use shims here: How to use requirejs with jQuery. Here you'll find the details of using shims when you have plugins that are not AMD compliant. In this case the problem and the solution is thoroughly explained for non AMD jQuery plugins, but way of working is exactly the same for ko plugins.

JotaBe
  • 38,030
  • 8
  • 98
  • 117