HEY! I'm working on an awesome course on Golang and Ember.js skills that's live soon. Get early access to it here:

nerdyworm

Infinite Scroll View With Ember.js

Here is a very simple example of how to create an infinite scroll view with Ember.js.

This is the view that will handle the window scroll event. We use the view event didInsertElement as a hook to bind to the window’s scroll event. We use an anonymous function that calls back to the view so that we guarantee that our function is called with this as the view.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
App.IndexView = Ember.View.extend({

  // When we insert this view into the dom bind the window's
  // scroll view to a function that executes our didScroll
  // function.
  didInsertElement: function() {
    var view = this;
    $(window).bind("scroll", function() {
      view.didScroll();
    });
  },

  didScroll: function() {
    // handle the awesomeness of didScroll
  }
});

Handling the more event

When the page hits the bottom of the window our app should load more items. The view should not know or care how to do that, so we delegate that to the view’s controller.

1
2
3
4
5
didScroll: function() {
  if(this.isScrolledToBottom()) {
    this.get('controller').send('more');
  }
}

The send method tries to invoke the action name on the controller. If the controller does not respond to the action name, then send tries the controller’s target and then the target’s target until the action is found or it runs out of targets.

1
2
3
4
5
6
7
App.IndexRoute = Ember.Route.extend({
  events: {
    more: function() {
      this.modelFor('index').loadMoreItems();
    }
  }
});

In this case the target of the view’s controller is the route. We can define the action in the routes events object. modelFor returns the model of the current route and then get can invoke the method to fetch more items.

Don’t forget to clean up the scroll event

When the view is destroyed we have to unbind the event. This is acomplished very easily by using the willDestroyElement view lifecycle callback.

1
2
3
4
// When this view is destroyed we need to unbind the scroll event.
willDestroyElement: function() {
  $(window).unbind("scroll");
}

A Complete Example

Here is a complete example based off the ember.js starter kit.

Github - Download

Enjoy!

Benjamin

Comments