How to get the next element of a knockoutjs observable array?

1k views Asked by At

I need to implement 2 buttons (next, previous) for array elements of an observable array. Is there any default function or any way to navigate between elements of the array?

Ex:

var mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);

When I click the next button, it should return the next object (like ko.utils.arrayFirst() returns the given object)

Any help?

1

There are 1 answers

0
Jeroen On BEST ANSWER

Nope, there is no "default" way to do this.

RoyJ's comment is spot on about how to do it yourself. Let me turn it into a working example:

var ViewModel = function() {
  var self = this;
  
  self.mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);
  
  var _currentItemIndex = ko.observable(0);
  
  function navigate(nrOfSpots) {
    if (_currentItemIndex() + nrOfSpots >= self.mainArray().length) { return; }
    if (_currentItemIndex() + nrOfSpots < 0) { return; }
    _currentItemIndex(_currentItemIndex() + nrOfSpots);
  }
  
  self.next = function() { navigate(1); };
  self.prev = function() { navigate(-1); };
  
  self.currentItem = ko.computed(function() {
    return self.mainArray()[_currentItemIndex()];
  });
};

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Current Item: 
<i data-bind="text: currentItem().name"></i>
<br />
<button data-bind="click: prev">Previous</button>
<button data-bind="click: next">Next</button>

It utilizes:

  • A private variable with an observable indicating the current index;
  • Two functions prev and next to change that index (for sofar valid/possible);
  • A computed to return the current item at that index.

The view (html) is just for demo purposes.