[英]How to get the next element of a knockoutjs observable array?
我需要為可觀察數組的數組元素實現2個按鈕(next,previous)。 是否有任何默認函數或任何方式在數組的元素之間導航?
例如:
var mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);
當我單擊下一個按鈕時,它應該返回下一個對象(如ko.utils.arrayFirst()返回給定對象)
有幫助嗎?
不,沒有“默認”方式來做到這一點。
RoyJ的評論是關於如何自己做的。 讓我把它變成一個工作的例子:
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>
它利用:
prev
和next
(對於sofar valid / possible); 視圖(html)僅用於演示目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.