Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout Mapping with requireJS

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/

like image 234
Not loved Avatar asked Dec 15 '25 16:12

Not loved


1 Answers

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.

like image 93
Sushanth -- Avatar answered Dec 17 '25 05:12

Sushanth --



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!