KnockoutJS return array from function
KnockoutJS return array from function– Sometimes we need to return array from the KnockoutJS function(View Model). It is very simple to return an array from a KnockoutJS function. Here in this tutorial we are going to explain how you can return array from view model function, you can also use our online editor to edit and run the online demo.
KnockoutJS return Array from function | computed Array Example
Let us create an example and return array from the function-
KnockoutJS return Array from function Example:
<!DOCTYPE html> <head> <title>KnockoutJS Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js" type="text/javascript"></script> </head> <body> <ul data-bind="foreach: weekdays"> <li> <span data-bind="text: dayno"></span> </li> </ul> <script> // data model content goes here var ViewModel = function() { this.weekdays = ko.computed(function() { var days = ko.observableArray([]); for(var i = 1; i<=7; i++){ days.push({dayno:i}); } return days(); // return days array }); }; ko.applyBindings(new ViewModel()); </script> </body> </html> |
In the above example we have create function weekdays which returns the array of the week days, we have used the returned array on UI ie view. We have used foreach binding to print the array value. On the same way you can return your array and use that on view.
If you run the above example it will produce the output something like this-
Advertisements