javascriptknockout.jsrequirejsknockout-components

KnockoutJS custom component loader not executing `loadViewModel`


Context

I have been fiddling around and trying to create my own (just another) SPA framework. In this framework I've been trying to create a custom component loader to be able to do some dependency injection 'n stuff on the viewModels I'm loading.

Used KnockoutJS version: 3.3.0

Problem

The loadViewModel function on the custom component loader isn't executing when a component is loaded.

Code for reference (see file):

injector(function (ko) {
    ko.components.loaders.unshift({
        getConfig: function (name, callback) {
            var parts = name.split("/");
            callback({
                require: "components/" + name + "/" + parts[parts.length - 1]
            });
        },
        loadViewModel: function (name, viewModelConfig, callback) {
            console.log(arguments);
            callback(null);
        }
    });
});

Please not that the injector function is just some custom dependency resolver I wrote. (Almost like a define or require call on AMD components.)

The getConfig function gets executed properly whatsoever.

For a complete overview of my doodling, see this git repo


Solution

  • If you don't "override" the loadComponent method then the default component loader's loadComponent will be invoked which only calls the loadViewModel if you've provided a viewModel config option.

    In your getConfig method you are returning a config with require which means that your require.js module has to provide the necessary viewModel config option.

    However in your viewModel.js the

    viewModel: func.apply(this.models[identifier], arguments) 
    

    does not correclty set the viewModel property which remained undefined