Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the component's viewmodel from component's node in KnockoutJS

I have a component named 'my-component':

ko.components.register('my-component', { 

    viewModel: function() {      
        return { title: 'title' };     
    },

    template: '<div>x</div>'

});

I'm using this component in the view like that:

<my-component params=""></my-component>

Is there any way to get the component's view-model related to this HTML node? ko.dataFor doesn't work:

ko.dataFor($('my-component').get(0)) // it doesn't return component's view model

Any thoughts?

like image 406
cryss Avatar asked Jun 11 '15 13:06

cryss


People also ask

What is Knockout ViewModel JS?

A ViewModel can be any type of JavaScript variable. In Example 1-3, let's start with a simple JavaScript structure that contains a single property called name .

What is $data in knockout JS?

This is the raw view model value in the current context. Usually this will be the same as $data , but if the view model provided to Knockout is wrapped in an observable, $data will be the unwrapped view model, and $rawData will be the observable itself.

How does Ko identify the template block that needs to be rendered?

Shorthand syntax: If you just supply a string value, KO will interpret this as the ID of a template to render. The data it supplies to the template will be your current model object.


1 Answers

Try this:

ko.dataFor($('my-component').get(0).firstChild);
like image 131
haim770 Avatar answered Oct 08 '22 05:10

haim770