Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access custom element in a Knockout component?

Take a look at this scenario :

ko.components.register('hello', {
     viewModel: function() { },
     template: "<h1>hello wrold</h1>"
});

If I use <hello></hello> the generated html result will be:

<hello><h1>hello world</h1></hello>

But what if I want this:

<hello class="hello"><h1>hello world</h1></hello>

Then how can I get a reference to the custom element tag in a component?

like image 263
amin Avatar asked Sep 13 '14 14:09

amin


People also ask

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is applyBindings in knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.

What is Ko observable?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.


1 Answers

The custom element contains the component, it is not considered part of it. Just like the outer tag used in a foreach, template or with binding. If you want to style that tag, you have to add the bindings to style it. The component will fill its contents.

<hello data-bind="css: 'hello'"></hello>

However if you absolutely wanted to access the parent element, I suppose it's possible but I would not recommend it. The component should only be concerned with itself, not the container that contains it. This can (and will) cause problems if the element had any child nodes that also had bindings.

Use a factory function for your view model. It will have access to the component's info (which currently only includes the containing element element)

ko.components.register('hello', {
    viewModel: {
        createViewModel: function (params, componentInfo) {
            var element = componentInfo.element;
            ko.applyBindingsToNode(element, { css: 'hello' });
            return {};
        }
    },
    template: "<h1>hello world</h1>"
});
like image 156
Jeff Mercado Avatar answered Oct 28 '22 03:10

Jeff Mercado