Call Custom function after binding customer name in magento2?
-
13-03-2021 - |
Question
I have updated the customer name using ko.
After binding customer name, I want to add one custom class.
<li class="customer-welcome">
<span class="customer-name"
role="link"
tabindex="0"
data-mage-init='{"dropdown":{}}'
data-toggle="dropdown"
data-trigger-keypress-button="true"
data-bind="scope: 'customer'">
<span data-bind="text: customer().fullname"></span>
<button type="button"
class="action switch"
tabindex="-1"
data-action="customer-menu-toggle">
<span><?php echo $block->escapeHtml(__('Change')) ?></span>
</button>
</span>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"customer": {
"component": "Magento_Customer/js/model/customer"
}
}
}
}
}
</script>
How to call the custom function after binding customer name.
Thanks.
Solution
app/code/Vendor/Module/view/frontend/templates/header/loginlink.phtml
Paste Below Span inside the My account section in loginlink.phtml file
<span class="bold" data-mage-init='{"js/loggedusername":{}}'>My Account</span>
Create a New js file named loggedusername.js in the below path
app/design/frontend/{theme}/{theme_name}/web/js/loggedusername.js
define([
"jquery", "Magento_Customer/js/customer-data"
], function($, customerData) {
"use strict";
return function (config, element) {
var firstname = customerData.get('customer')().firstname;
if (typeof (firstname) === "undefined") {
customerData.reload('customer');
}
var check = setInterval(function () {
var firstname = customerData.get('customer')().firstname;
if (firstname) {
$(element).text('Hi, ' + firstname);
$(element).addClass('your_class_name_here')
clearInterval(check);
}
}, 500);
};
});
In this solution not based on knockout js, But it works perfectly .Please follow if you want , Thank you.
OTHER TIPS
Try below method...
<span data-bind="text: customer().fullname, css: {
'custom-class' : customer().fullname
}">
</span>
Not tested in my env
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange