javascript - 如何在 MithrilJS 中进行分页?

标签 javascript pagination mithril.js

我的内存中有一个包含大约 50 个项目的数据集,我正在尝试为此数据集创建一个分页器,但我不确定如何执行此操作。

我正在使用自定义过滤器函数来过滤结果,效果很好,但不知何故我需要获取页数。

有什么线索吗?

最佳答案

Mithril Infinite是一种多功能 Mithril 组件,用于处理潜在的大量元素集合。它的主要目的是作为一个潜在的无限滚动列表,但它的 Github 页面还具有 a pagination demo 功能。 .

分页本身不应该是一个困难。最简单的分页需要一个有状态的索引来指示要显示的页面,以及一种将列表拆分为子列表来表示页面的方法。

关键是一个好的 reducer 函数,可以从我们的初始项目列表中创建页面列表:

// The initially empty collection of pages is the first argument.
// The function executes once for each item in a provided list like forEach & map.
function paginate( pages, item, index ){
  // Modulo (%) is the remainder of x after division by y
  // A result of 0 means a multiple. 
  // So if pageLength is 6, we would create a new page at 0, 6, 12, 18, etc...
  if( index % pageLength === 0 )
    pages.push( [] )

  // Push the item onto the last page
  pages[ pages.length - 1 ].push( item )

  // Return the pages
  return pages
}

然后您需要在组件 View 中的列表上调用此函数:

var FilteredPages = {
  controller : function(){
    this.filter = ''
    this.index  = 0 
  },

  view : function( ctrl, pageLength, items ){
    return m( '.FilteredPages',
      m( 'input', {
        value : ctrl.filter,
        oninput : function(){
          ctrl.filter = this.value
          ctrl.index  = 0 
        }
      } ),

      m( 'p', 
        m( 'a', {
          innerHTML : 'Back',
          onclick   : function(){
            if( ctrl.index > 0 )
              ctrl.index--
          }
        } ),

        ' ',

        m( 'a', {
          innerHTML : 'Next',
          onclick   : function(){
            var newIndex = ctrl.index + 1

            if( newIndex < items / pageLength )
              ctrl.index = newIndex
          }
        } )
      ),

      m( '.page', 
        items
          // Filter the items according to your requirements
          .filter( function( item ){ return item.includes( ctrl.filter ) } )
          // Paginate the filtered list using our reducer
          .reduce( paginate, [] )
          // Take the page at the current index
          [ ctrl.index ]
            // Map over the items on this page
            .map( function( item ){
              // Produce a view for each item
              return m( 'p', item )
            } ) 
      )
    )
  } 
}

关于javascript - 如何在 MithrilJS 中进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463204/

相关文章:

javascript - 从嵌套对象中并行数组的属性获取总计

c# - 如何在 C# 中获取 azure Devops Rest api 调用的连续 token 以获取所有测试运行?

python - 用 Python 抓取分页

javascript - 如何检查 mithril.js 是否已加载?

url-routing - 如何使用子组件(子组件)执行 Mithril 路由

javascript - 如何在 MVC3 中将 Javascript 变量设置为模型字符串数组?

javascript - 我将如何使用 Socket-IO 上传图像文件?

javascript - RxJS 过滤日期

java - 如何对长文本帖子进行分页

javascript - 迭代 Mithril 中的字符串列表并创建下拉列表