Search code examples
knockout.jsknockout-2.0knockout-components

Params with knockout component using instance


I would like to send in params to an "instance" (singleton) of my knockout component using requirejs. The knockout help only shows examples of non instance parameter passing.

i have the following code which uses the instance and works correctly.

 //module declaration
 function unapAppointments()
{
      rest of code here.
}
 return {
        viewModel: {
            instance: new unapAppointments()
        },
        template: unapp,

    };

What i would like to do is something like the below passing in PARAMS from the component. This however obviously does not work.

 //module declaration
     function unapAppointments(PARAMS)
    {
          use PARAMS
    }
 return {
        viewModel: {
            instance: new unapAppointments(PARAMS)
        },
        template: unapp,

    };

Thanks


Solution

  • Returning a new instance depending on params contradicts the use of a shared instance viewmodel. This is exactly like using the viewmodel as constructor (accepting params) approach.

    If you want to create a single instance, modify its internals depending on params each time before the binding is applied, you can use the createViewModel factory:

    define(['knockout', 'text!./unapp.html'], function(ko, unapp) {
    
        function unapAppointments() {
            // rest of code here.
        }
    
        var mySingleton = new unapAppointments();
    
        function unapAppointmentsFactory(params, componentInfo) {
            // modify mySingleton using params
            return mySingleton;
        }
    
        return {
            viewModel: {
                createViewModel: unapAppointmentsFactory
            },
            template: unapp,
        };
    });
    

    But using this approach is delicate. If there is multiple components in the page, the last one to be bound wins, its params will override all the others.