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?

我需要为可观察数组的数组元素实现2个按钮(next,previous)。是否有任何默认函数或任何方式在数组的元素之间导航?

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?

1 个解决方案

#1


2

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:

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>

更多相关文章

  1. 使用Jquery Ajax更改按钮的颜色(从外部PHP文件接收颜色)
  2. 显示json数组中的所有项目
  3. 图表。js数据数组使用PHP, MySQL。如何从JSON数组定义数据源?
  4. 将JavaScript对象转换为要插入关系数据库的数组
  5. javascript数组和对象是否有设置顺序?
  6. 从另一个数组中删除数组的内容。
  7. 从两个数组生成JSON
  8. 在单选按钮上选中/取消选中,加载/隐藏部分视图
  9. 如何将图像(PNG)转换为2D数组(二进制图像)?

随机推荐

  1. Android面试系列文章2018之Android部分之
  2. Android中AsyncTask的简单用法及实现网络
  3. Android之分享篇(配图适合新人):腾讯分享(QQ
  4. Android P 图形显示系统(九) Android图形显
  5. android之调用webservice 实现图片上传
  6. Android内核开发:源码的版本与分支详解
  7. Android中View.setPressed是怎么出现按压
  8. Google:Android 2.3在所有Android系统设备
  9. 搭建Android应用程序的服务器
  10. Android游戏Graphics绘图之图像像素操作