Re: [KnockoutJS] How to pass params to typescript class instantiation?

166 views
Skip to first unread message

Karim Ayachi

unread,
Aug 31, 2020, 3:18:58 AM8/31/20
to knock...@googlegroups.com
Hi Mario,

The problem is not that the class is not instantiated, but that your module loader does not know which export to use (you're just pointing to a file).

Since Knockout 3.5.1 you can use the default export for this, as added by this pull request: https://github.com/knockout/knockout/pull/2483

export default class MyComponent {  
}

That should allow TypeScript transpiled classes to be loaded with an AMD module loader as in your example.

Is your second question ('how to pass parameters?') still relevant if you do it like this?

Regards

On Sat, Aug 29, 2020 at 6:14 AM Mario Valle <silicon...@gmail.com> wrote:
I want to create components with typescript and registering them with:

    ko.components.register("my-component", {
viewModel: {require: "widgets/my-component"},
template:  {require: "text!widgets/my-component.html"}
    });

The component is a typescript class:

    export class MyComponent {
constructor(private params) {
...

But this generate an error at runtime because the class is not instantiated:
`Uncaught Error: Component 'my-component': Unknown viewModel value: [object Object]`

I think I have to change my typescript definition to export an instance of MyComponent, but I don't know how to pass the params to the constructor.

    `const inst = new MyComponent(???); export inst;`

Any Idea?
Thanks!
mario

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/knockoutjs/6cb98e11-9639-46a1-b8f9-b86724ee30f8n%40googlegroups.com.

Mario Valle

unread,
Dec 14, 2020, 12:22:34 AM12/14/20
to KnockoutJS
Thanks! I found the solution. At the end of each component class definition just add:

// Makes the class ComponentWidgetViewModel  available as a ViewModel
function getViewModel(paramsComponentParams): ComponentWidgetViewModel {
    return new ComponentWidgetViewModel(params);
}
export = getViewModel;

Hope it helps
mario

Reply all
Reply to author
Forward
0 new messages