3
votes

I would like to use RequireJS to manage plugins in my site. I use knockout with the mapping plugin and I was reading the following answer https://stackoverflow.com/a/16449509/1070291 and I'm having a bit of trouble getting it going.

The callback seems to run after the actual require() statement, which means ko.mapping isn't defined

Any idea what I'm missing?

<script>
    var require = {
        paths: {
            "knockout": "//cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min",
            "mapping": "//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping"
        },
        deps: ['knockout', 'mapping'],
        callback: function (ko, mapping) {
            ko.mapping = mapping;
        }
    };
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js"></script>
<script>
    require(['knockout'], function (ko) {
        alert( 'ko: ' + ko + ', mapping: ' + ko.mapping);
    });
</script>

JsFiddle here: http://jsfiddle.net/WLegU/2/

1

1 Answers

2
votes

You were almost close to get it working. The only missing part is that you need to require even the mapping module, which in turn calls the callback first because it is a dependency.

require(['knockout', 'mapping'], function (ko) {
    console.log( 'ko: ' + ko + ', mapping: ' + ko.mapping );
});

Check Fiddle

From the docs

This callback function will be called when all the dependencies listed above in deps are loaded.

Because you were not requiring the mapping module, the callback was invoked later when the mapping module was loaded.