0

I have a very simple Component

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function (Component, customerData) {
    'use strict';

    return Component.extend({
        /** @inheritdoc */
        initialize: function () {
            this._super();

            this.notificationCounts = customerData.get('notification_counts');
        }
    });
});

I want to conditionally display an html element based on whether I have or not have any notifications.

I managed to do so with the following template:

<span data-bind="scope: 'notificationCounts'">
    <span id="some-id"data-bind="visible: notificationCounts().count">
         ... more content here ...
    </span>
</span>

<script type="text/x-magento-init">
    {
    
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "notificationCounts": {
                        "component": "Vendor_Module/path/to/js"
                    }
                }
            }
        }
    }
</script>

However, I would like to get rid of the first wrapping span. This is how I changed the template (only relevant parts)

    <span id="some-id" data-bind="scope: 'notificationCounts', visible: notificationCounts().count">
             ... more content here ...
    </span>

But now I get the following console error:

Unable to process binding "visible: function(){return notificationCounts().count }

Any idea how I can get rid of the extra wrapping span? Maybe some ko directive I'm missing.

Any hints are appreciated.

Thanks

1 Answer 1

0

Here are all the ways you can define the scope in a template:

<!-- as an attribute -->
<div ko-scope="'name.of.component'"></div>

<!-- in a standard KO form -->
<div data-bind="scope: 'name.of.component'"></div>

<!-- without an extra container node -->
<scope args="'name.of.component'"></scope>

<!-- as a virtual element -->
<!-- ko scope: name.of.component --><!-- /ko -->

source: https://developer.adobe.com/commerce/frontend-core/ui-components/concepts/knockout-bindings/

So for the code in the question we are going to use a virtual element to achieve our goal:

<!-- ko scope: 'notificationCounts' -->
    <span id="some-id" data-bind="visible: notificationCounts().count">
                 ... more content here ...
    </span>
<!-- /ko -->

That's it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.