[英]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. 我需要为可观察数组的数组元素实现2个按钮(next,previous)。 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) 当我单击下一个按钮时,它应该返回下一个对象(如ko.utils.arrayFirst()返回给定对象)
Any help? 有帮助吗?
Nope, there is no "default" way to do this. 不,没有“默认”方式来做到这一点。
RoyJ's comment is spot on about how to do it yourself. RoyJ的评论是关于如何自己做的。 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: 它利用:
prev
and next
to change that index (for sofar valid/possible); prev
和next
(对于sofar valid / possible); The view (html) is just for demo purposes. 视图(html)仅用于演示目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.