简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM