How listens javascript uiComponent property works with magento 2?

A listens property of UI Component in Magento is used to track changes of a component’s property.

Any observable property changes happened, a function defined with listens property calls.

Let’s understand the listens:{} property with a simple example,

Create simple .phtml template file with input field text type using knockout data-bind,

<?php declare(strict_types=1);
// template file
?>

<script type="text/x-magento-init">
    {
        "*" : {
             "Magento_Ui/js/core/app": {
                "components" : {
                    "listensExample" : {
                        "component" : "Jesadiya_Blog/js/listner-example"
                    }
                }
             }
        }
    }
</script>
<div data-bind="scope: 'listensExample'">
    <label>First Name</label>
    <input data-bind="textInput: firstname" />

    <label>Hobby</label>
    <input data-bind="value: hobby" />
</div>

In the given template file, We have created a custom component called listensExample and assigned it to the DOM element with scope.

Create JS file, app/code/Jesadiya/Blog/view/frontend/web/js/listner-example.js

define(['uiComponent'], function (Component) {
   'use strict';

    return Component.extend({
        defaults: {
            firstname: 'Enter First Name',
            hobby: 'Cricket',
            listens: {
                firstname: 'getFirstname',
                hobby: 'updateHobby'
            }
        },
        getFirstname: function (value) {
            console.log('updatedValue' , value);
        },
        updateHobby: function (hobbyUpdate) {
            console.log(hobbyUpdate);
        },
        
        /**
         * Observe the current property
         * @returns {*}
         */
        initObservable: function () {
            this._super().observe(['firstname', 'hobby']);
            return this;
        }
    });
});

A listens property works with only observable, so we need to create firstname and hobby field as observable.

Here in the template file,

<input data-bind="textInput: firstname" />

A first name text field will be called on each key-up event. once you type any character in the first name field, getFirstname() method will be called.

If you want to call a method on blur of the text field, you can use the data-bind value property.

<input data-bind="value: hobby" />

The data-bind textInput will be called always an update or change the field value.

The data-bind value will be called once you blur the current text field.


Real Example from Magento Frontend,
In Magento, You can see listens property used in the guest checkout page with a login form.

Once you made any changes to the email field, listens will call function to track email is available or not in the system.

You can check more details of listens property from the core Javascript file, vendor/magento/module-ui/view/base/web/js/lib/core/element/element.js