简体   繁体   中英

Knockout custom component with data-bind text

I have a custom component, let's call it mycomp , that accesses text it's passed in its template like this:

<p>
    <!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->
</p>

I use this component in another component and try to pass a text to it like this:

<mycomp data-bind='text: myProperty'></mycomp>

When I try to run this, I get

Unable to process binding "component: function(){return l}"
Message: Multiple bindings (text and component) are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.

Is there a way to fix the issue and do what I want to do, namely use a component in another component and pass it text via data-bind='text: ...' ?

"text" binding only makes sense when used with native dom elements (div, span, etc) or virtual elements as it's changes all the element content with the specified text.

This is what the error message is saying (both, "text binding" and the component itself are trying to change the content).

Your component seems to output all the template nodes, so I think it will work if you do this:

<mycomp>hello</mycomp>

After your update, I think you have 2 options:

<mycomp>
    <!-- ko text: myProperty --><!-- /ko -->
</mycomp>

Or create custom parameter for your component, so you can do this:

<mycomp params="text: myProperty"></mycomp>

Details on how to to this are here => https://knockoutjs.com/documentation/component-overview.html

In your case, I think it would be like this:

ko.components.register('mycomp', {
    viewModel: function(params) {
        this.text= params.text;
    },
    template:
        '<p data-bind="text: text"></p>'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM