Skip to content

Magento2. KnockoutJs. Define Scope and call function on the same html node

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