Search code examples
knockout.jsknockout-mapping-plugindurandal

How to use knockout mapping plugin with Durandal?


I'm new in Durandal, and wanted to rewrite my existing knockout project using this framework. In my old project I'm using knockout mapping plugin and now I have problem with it. I work with Durandal sample project as a base. Here is my piece of code:

define(['durandal/app', 'durandal/system', 'knockout'], function (app, system, ko) {

    var clients = ko.observableArray([]);

    return {    
        clients: clients,

        activate: function(data) {
            var self = this;
            ko.mapping.fromJS(getData(), {}, self.clients);
        }
    };
};

The error is:

Uncaught TypeError: Cannot call method 'fromJS' of undefined

Indeed, it is undefined, but where should I add it and make it working?

Thanks.


Solution

  • You should add the mapping plugin in the defineotherwise is not going to load it.

    define(['durandal/app', 'durandal/system', 'knockout', 'knockout-mapping'], function (app, system, ko) {
    

    Make sure you able to load this script like this in your requirejs configuration.

    I suggest that you load Knockout and the mapping plugin in the main.jsso you don't need to keep "requiring" them in all the viewmodels. You can also bundle them separately and not be part of the loader.