ember-model
ember-model copied to clipboard
Allow library users to subclass RecordArray
In our first attempt at infinite scrolling, we would fetch the first page of results in the route and then fetch the subsequent pages in the component that handled lazy loading. It became a bit of a mess once we had different types of objects we were lazy loading. We reimplemented it so that the RecordArray knew how to load the next page of results. Here's a trimmed down example (in coffeescript) of how we are using a subclass of RecordArray to support lazy-loading:
App.PagedRecordArray = Ember.RecordArray.extend
appendNextPage: ->
query = Em.copy(@get('_query'))
query.page = (query.page or 0) + 1
@get('modelClass').fetchQuery(query).then (results)=>
@addObjects results
results
App.Merchant = Em.Model.extend
id: Em.attr()
name: Em.attr()
App.Merchant.recordArrayClass = App.PagedRecordArray
In the route we use App.Merchant.fetchQuery() to get the initial set of merchants. Then when our component needs to load more merchants, it just calls merchants.appendNextPage(). Ember's observers take care of loading the new content into the page.
Here's the commit we're currently using to change the record array class: https://github.com/zipfworks/ember-model/commit/4525c206f00539a2e6d05c2ed55b40a61bf9adaa . I'd like to turn that into a pull request with tests and such, but I'd like some feedback first. In particular:
- After creating the
PagedRecordArray, I realized I could get the same effect by usingEmber.RecordArray.reopenClass. Should we do that instead? - Right now the query used to create a RecordArray is sometimes stored on the RecordArray on the presumably private
_query. Can we make the query used to create a record array part of its public interface? It would be null forfindAll, the query forfindQuery, and the array of ids forfindMany.
I also found that having a subclass of RecordArray and access to the _query is nice for changing the filters on a query.
:+1: