无限滚动与ember.js(延迟加载)

out*_*344 54 lazy-loading infinite-scroll ember.js ember-data

我有一个视图,其中可以有大量的项目供用户滚动,我想实现无限滚动以启用内容的渐进加载.

看起来有些人已经完成了分页,但谷歌没有提出任何讨论他们如何使用Ember/Ember Data完成无限列表的人.任何人都已经完成了这个并有一个博客文章/示例代码分享?

pan*_*atz 61

我实现了在一个无限滚动机制GitHub Dashboard 项目,我目前正在开发.该功能在commit 68d1728中添加.

基本思想是每当视图在当前视口上可见时,都会在控制器上LoadMoreView调用该loadMore方法.我正在使用jQuery插件inview.它允许您注册一个inview事件,当指定选择器的元素在屏幕上可见并且它消失时触发该事件.

控制器还具有指示是否有更多项目要加载以及是否有当前获取的项目的属性.这些属性被称为canLoadMoreisLoading.

LoadMoreView基本上是这样的:

App.LoadMoreView = Ember.View.extend({
  templateName: 'loadMore',
  didInsertElement: function() {
    var view = this;
    this.$().bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
      if (isInView) Ember.tryInvoke(view.get('controller'), 'loadMore');
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

其中loadMore模板定义如下:

{{#if isLoading}}
    fetching some more stuff <img width="10" src="img/ajax-loader.gif" >
{{else}}
    {{#if canLoadMore}}
        <a {{action "loadMore" target="controller" }}>click to load more items</a>
    {{else}}
        <i>no more items</i>
    {{/if}}
{{/if}}
Run Code Online (Sandbox Code Playgroud)

然后如下实现处理获取更多项目的控制器.请注意,在该loadMore方法中,执行对商店的查询,该查询加载模型的特定条目页面.

App.EventsController = Ember.ArrayController.extend({
  currentPage: 1,

  canLoadMore: function() {
    // can we load more entries? In this example only 10 pages are possible to fetch ...
    return this.get('currentPage') < 10;
  }.property('currentPage'),

  loadMore: function() {
    if (this.get('canLoadMore')) {
      this.set('isLoading', true);
      var page = this.incrementProperty('currentPage');

      // findQuery triggers somehing like /events?page=6 and this
      // will load more models of type App.Event into the store
      this.get('store').findQuery(App.Event, { page: page });
    } else {
      this.set('isLoading', false);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

剩下的唯一事情是最初将content控制器设置为filter函数的结果,因此在content将新模型加载到存储中时会更新(由于控制器中的findQuery方法而发生loadMore).此外,调用query时会添加哈希filter.这可确保对服务器进行初始查询.

App.eventsController = App.EventsController.create({
    content: []
});

var events = App.store.filter(App.Event, { page: 1 }, function(data) {
    // show all events; return false if a specific model - for example a specific
    // type of event - shall not be included
    return true;
});
Run Code Online (Sandbox Code Playgroud)

  • 非常有帮助,但你为什么要使用过滤器?你实际上并没有过滤任何东西(即`return true`),那么使用过滤器还有其他好处吗? (3认同)
  • 我真的没有完成最后一步,`var event = ...`.为什么保存在变量中?使用的变量在哪里以及过滤器的用途是什么? (3认同)

com*_*ted 15

你知道新发布的Ember.ListView组件吗?

https://github.com/emberjs/list-view

它在2月旧金山Ember Meetup上宣布.这是Erik Bryn的一个幻灯片,Erik Bryn是Ember Core开发人员之一,使用它:

http://talks.erikbryn.com/ember-list-view/


iHi*_*HiD 5

我正根据@ pangratz的作品为Ember写一个无限的分页插件.

如果您有任何疑问或改进,请在那里解决任何问题.