You can write a custom observable function to include all of your functions:
ko.showMoreArray = function(initial) { var observable = ko.observableArray(initial); //observables to change behaviour observable.limit = ko.observable(3).extend({numeric:true}); observable.showAll = ko.observable(false); //function to toggle more/less observable.toggleShowAll = function() { observable.showAll(!observable.showAll()); }; //computed observable for filtered results observable.display = ko.computed(function() { if (observable.showAll()) { return observable(); } return observable().slice(0,observable.limit()); }, observable); return observable; };
It really just wraps up what you already wrote, but it is reusable and leaves your HTML much neat:
<input data-bind="value: $root.orders.limit, valueUpdate: 'afterkeyup'" /><br/> <ul data-bind="foreach: orders.display"> <li data-bind="text: $data"></li> </ul> <a data-bind="text: orders.showAll() ? 'Less options' : 'More options', click: orders.toggleShowAll" href="#"></a>
I put the working version on jsFiddle .
In the above example, you need to bind to the display property in the original array, but otherwise it will behave like a βfullβ array to all of your code (which I think makes more sense overall). However, if you prefer it to behave as a filtered (i.e. a maximum of 3 elements) array to your code, then you can achieve this in the same way as shown here
source share