Call function during data binding in Knockout JS
In this example, We will show you example of How to Call function during data binding in Knockout JS. The output has been shared in the same post.
Script Code
ko.applyBindings({result:[{"month":"3"}, {"month":"4"}, {"month":"7"}, {"month":"10"}, {"month":"9"}, {"month":"12"}, {"month":"1"}, {"month":"2"}, {"month":"6"}, {"month":"5"}, {"month":"8"}, {"month":"11"}]}); function getMonthName(month) { var monthName = ""; // Coverting String to Integer month = parseInt(month); switch(month) { case 1: monthName = "Jan"; break; case 2: monthName = "Feb"; break; case 3: monthName = "Mar"; break; case 4: monthName = "Apr"; break; case 5: monthName = "May"; break; case 6: monthName = "Jun"; break; case 7: monthName = "Jul"; break; case 8: monthName = "Aug"; break; case 9: monthName = "Sep"; break; case 10: monthName = "Oct"; break; case 11: monthName = "Nov"; break; case 12: monthName = "Dec"; break; default: monthName = "NA"; break; } return monthName; }
Calling Function during Data Binding
data-bind = “text: getMonthName(month)”
Complete Example
<html> <head> <title>How to Call function during data binding in Knockout JS</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-debug.js"></script> </head> <body> <h1>How to Call function during data binding in Knockout JS</h1> <table cellpadding = "5" cellspacing = "5" border = "1"> <thead> <tr> <th>Month Number</th> <th>Month Name</th> </tr> </thead> <tbody data-bind="foreach: result"> <tr> <td data-bind = "text: month"></td> <td data-bind = "text: getMonthName(month)"></td> </tr> </tbody> </table> <script> ko.applyBindings({result:[{"month":"3"}, {"month":"4"}, {"month":"7"}, {"month":"10"}, {"month":"9"}, {"month":"12"}, {"month":"1"}, {"month":"2"}, {"month":"6"}, {"month":"5"}, {"month":"8"}, {"month":"11"}]}); function getMonthName(month) { var monthName = ""; // Coverting String to Integer month = parseInt(month); switch(month) { case 1: monthName = "Jan"; break; case 2: monthName = "Feb"; break; case 3: monthName = "Mar"; break; case 4: monthName = "Apr"; break; case 5: monthName = "May"; break; case 6: monthName = "Jun"; break; case 7: monthName = "Jul"; break; case 8: monthName = "Aug"; break; case 9: monthName = "Sep"; break; case 10: monthName = "Oct"; break; case 11: monthName = "Nov"; break; case 12: monthName = "Dec"; break; default: monthName = "NA"; break; } return monthName; } </script> </body> </html>
Output
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet