【问题标题】:How to do paging in MithrilJS?如何在 MithrilJS 中进行分页?
【发布时间】:2017-01-20 15:39:08
【问题描述】:

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

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

有什么线索吗?

【问题讨论】:

    标签: javascript pagination mithril.js


    【解决方案1】:

    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
    }
    

    然后你需要在你的组件视图中调用你的列表:

    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 )
                } ) 
          )
        )
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2019-08-17
      • 2017-10-03
      • 2012-06-04
      • 2014-05-08
      • 2019-08-22
      • 2021-03-16
      • 2019-12-30
      • 2019-01-15
      相关资源
      最近更新 更多