• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An Ember Addon that puts the fun back in asynchronous, paginated datasets

Ember-Impagination

npm version Ember Observer Score Build Status Netlify Status

Ember-Impagination is an Ember binding for Impagination, a front-end data-layer for the paginated API on your server. Ember-Impagination leverages the power of Glimmer and provides your component the data it needs to render quickly each and every time.

Impagination README: Whatever your use-case: infinite scrolling lists, a carousel browser, or even a classic page-by-page result list, Impagination frees you to focus on what you want to do with your data, not the micro-logistics of when to fetch it. All you provide Impagination is the logic to fetch a single page, plus how many pages you want it to pre-fetch ahead of you, and it will figure out the rest. Impagination is built using an event-driven immutable style, so it is ideal for use with UI frameworks like Ember . . .

Hence, we present Ember-Impagination.

Ember-Impagination provides you with a component, {{impagination-dataset as |data|}}, you can use to feed data into your templates while having that data look exactly like an Ember.Array.

Note: Ember-Impagination does not provide any of the visual elements in a system like infinite scroll. You'll still need to use a special component like virtual-each or ember-collection. Instead, Ember-Impagination simplifies feeding your components fetched data.

Installation

  • ember install ember-impagination

Demo

Ember-Impagination Demo

The demo presents a finite scroll implementation of Ember-Impagination. It scrolls through the ROYGBIV color spectrum by loading and unloading pages of records, where each record is a unique color-hue. At the top of the demo, you will find a visualization for pages. Resolved (Loaded) Pages are green, Pending (Loading) pages are white, and Unrequested (Unloaded) pages are black. The white-bar represents the top-most index of the scroll view.

ember-impagination

The demo is implemented using virtual-each due to the simplicity of the component. However, Ember-Impagination can also be utilized with other components like ember-collection, or even a simple {{each}}. By design, Ember-Impagination leverages Glimmer and yields paginated data from your server's API to components which expect an array.

Usage

Impagination-Dataset Component

To create an impagination-dataset there are two required parameters, fetch and page-size. Optional parameters include load-horizon, unload-horizon, unfetch. See Impagination for detailed attribute descriptions.

{{!-- app/templates/index.hbs --}}
{{#impagination-dataset
  fetch=fetch
  page-size=pageSize
  load-horizon=loadHorizon
  as |records|}}
  <div class="records">Total Records: {{records.length}}</div>
  {{#each records as |record|}}
    <div class="record">Record {{record.content.id}}</div>
  {{/each}}
{{/impagination-dataset}}

Now, in your route, you can define the actual (un)fetch functions that tell {{impagination-dataset}} how it should request each individual page, and the (un)loadHorizon which specify how many pages to request ahead/behind.

// app/route/record.js
export default Ember.Route.extend({
  pageSize: 5, // fetch records in pages of 5 (*required*)
  loadHorizon: 10, // fetch  records "inclusive" (+/- loadHorizon)   of the current readOffset (default: pageSize)
  //unloadHorizon: Infinity, // unload records "exclusive" (+/- unloadHorizon) of the current readOffset (default: Infinity)
  //readOffset: 0,           // the initial readOffset of the dataset (default: 0)

  // fetch() function is invoked whenever a page is requested within the loadHorizon
  fetch: function(pageOffset, pageSize, stats) {
    // function which returns a "thenable" (*required*)
    let params = {
      page: pageOffset
    };
    // fetch a page of records at the pageOffset
    return this.store.query("record", params).then(data => {
      let meta = data.get("meta");
      stats.totalPages = meta.totalPages;
      return data.toArray();
    });
  },
  // unfetch() function is invoked whenever a page is unloaded
  unfetch: function(records, pageOffset) {
    this.store.findByIds(
      "record",
      records
        .map(r => r.id)
        .then(function(records) {
          records.forEach(record => record.deleteRecord());
        })
    );
  }
});

This setup will immediatly call fetch twice (for records 0-4 [page 0] and records 5-9 [page 1])


Total Records: 10
Record 0
Record 1
Record 2
...
Record 9

Passing the Fetch Function

In Ember 1.13 and above, we can use closure-actions to pass the fetch function into ember-impagination

{{#impagination-dataset fetch=(action "fetch")}}
// app/route/record.js
export default Ember.Route.extend({
  // fetch() function is invoked whenever a page is requested within the loadHorizon
  actions: {
    fetch(pageOffset, pageSize, stats) {
      // function which returns a "thenable" (*required*)
      let params = {
        query: query
      };
      // fetch a page of records at the pageOffset
      return this.store.query("record", params).then(data => {
        let meta = data.get("meta");
        stats.totalPages = meta.totalPages;
        return data.toArray();
      });
    }
  }
});

We do not recommend defining fetch inside your controller because it requires injecting the store into the controller

In Ember 1.12 and below we cannot define fetch in our actions hash. We must instead bind it to our controller.

{{#impagination-dataset fetch=fetch)}}
// app/route/record.js
export default Ember.Route.extend({
    fetch: function(pageOffset, pageSize, stats) {
      return this.store.query(...);
    },
    setupController: function(controller, model){
      this._super.apply(this, arguments);
      controller.set('fetch', this.fetch.bind(this));
    }
});

Filtering Records

We fetch records using an immutable style, but we often require filtering by mutable records in our dataset. To enable filtering, pass a filter callback to ember-impagination as you would to Array.prototype.filter(). The filters are applied as soon as a page is resolved. To filter a page at other times in your application see refilter.

{{#impagination-dataset fetch=(action "fetch") filter=filterCallback}}
// app/route/record.js
export default Ember.Route.extend({
  // filter() function is invoked whenever a page is resolved or refiltered
  filterCallback(record /*, index, records*/) {
    // function which rejects deleted records
    return !record.get("isDeleted");
  }
});

Dataset API

There are a number actions to update the dataset.

Updating the Dataset

Actions Parameters Description
refilter [filterCallback] Reapplies the filter for all resolved pages. If filterCallback is provided, applies and sets the new filter.
reset [offset] Unfetches all pages and clears the state. If offset is provided, fetches records starting at offset.
setReadOffset [offset] Sets the readOffset and fetches records resuming at offset
reload [index] Removed in 1.0.0 release. Please use reset instead.

Updating the State

Actions Parameters Defaults Description
post data, index index = 0 Creates record with data at index.
put data, index index = state.readOffset Merges data into record at index.
delete index index= state.readOffset Deletes record at index.

These functions can be called from the route/controller or from child components in the handlebars templates. In the examples below, we reset the dataset upon search queries through the {{search-pane}} component using both options.

resetting from the parent route

In order to call dataset actions from the route, we will have to observe the latest dataset and dataset-actions with the on-observe parameter.

{{#search-pane search=(action "search")}}
  {{#impagination-dataset on-observe=(action "observeDataset") fetch=(action "fetch") as |dataset|}}
    {{#ember-collection items=dataset as |record|}}
      {{chat-search-result result=record}}
    {{/ember-collection}}
  {{/impagination-dataset}}
{{/search-pane}}
_resetDataset() {
  this.get('dataset').reset();
},

actions: {
  observeDataset: function(dataset) {
    this.set('dataset', dataset);
  },
  search(query) {
    this.set('searchParams', query);
    this._resetDataset();
  },
  fetch(pageOffset, pageSize, stats) {
    params = this.get('params');
    return this.store.query('records', params);
  }
}

resetting from child components

Here we do not need to utilize impagination-dataset's on-observe parameter. The reset action is simply called by a child component.

{{#impagination-dataset fetch=(action "fetch") as |dataset|}}
  {{!-- reset dataset and start fetching at record index 0 --}}
  {{#search-pane search=(action "search") on-search-results=(action dataset.reset 0)}}
      {{#ember-collection items=dataset as |record|}}
        {{chat-search-result result=record}}
      {{/ember-collection}}
  {{/search-pane}}
{{/impagination-dataset}}

Create your own Dataset

If {{impagination-dataset}} is not an ideal component for your unique Impagination needs, you can get into the nitty gritty, and use Impagination directly. If you find yourself creating your own Dataset, let us know how you are using Dataset and Impagination. It may be a reason for improvements or another ember addon.

import Dataset from 'impagination/dataset';

let dataset = new Dataset({
  pageSize: 5,
  fetch: function(pageOffset, pageSize, stats) {
    return new Ember.RSVP.Promise((resolve)=> {
      let data = // Array
      resolve(data);
    },

    return this.store.query('record', params).then((data) => {
      let meta = result.get('meta');
      stats.totalPages = meta.totalPages;
      return result.toArray();
    });
  },
  observe: (state) => {}
});

Running tests

  • ember test – Runs the test suite on the current Ember version
  • ember test --server – Runs the test suite in "watch mode"
  • ember try:each – Runs the test suite against multiple Ember versions

Running the dummy application

For more information on using ember-cli, visit https://ember-cli.com/.

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms, which can be found in the CODE_OF_CONDUCT.md file in this repository.

License


This project is licensed under the MIT License.

More Repositories

1

ember-electron

⚑ Build, test, compile and package desktop apps with Ember and Electron
JavaScript
806
star
2

ember-cp-validations

Ember computed property based validations
JavaScript
443
star
3

ember-changeset

Ember.js flavored changesets, inspired by Ecto
JavaScript
431
star
4

ember-moment

JavaScript
399
star
5

ember-infinity

⚑ Simple, flexible Infinite Scroll for Ember CLI Apps.
JavaScript
377
star
6

ember-data-model-fragments

Ember Data addon to support nested JSON documents
JavaScript
371
star
7

ember-metrics

Send data to multiple analytics integrations without re-implementing new API
JavaScript
367
star
8

ember-cli-flash

Simple, highly configurable flash messages for ember-cli
JavaScript
355
star
9

ember-light-table

Lightweight, contextual component based table for Ember
JavaScript
312
star
10

ember-data-factory-guy

Factories and helper functions for (unit, integration, acceptance) testing + development scenarios with Ember Data
JavaScript
302
star
11

ember-sortable

Sortable UI primitives for Ember.js
JavaScript
295
star
12

ember-burger-menu

An off-canvas sidebar component with a collection of animations and styles using CSS transitions
JavaScript
279
star
13

ember-cli-sass

Use node-sass to preprocess your ember-cli app's files, with support for sourceMaps and include paths
JavaScript
276
star
14

ember-notify

Notification messages for your Ember.js app
JavaScript
264
star
15

ember-collection

An efficient incremental rendering component for Ember.js with support for custom layouts and large lists
JavaScript
236
star
16

ember-changeset-validations

Validations for ember-changeset
JavaScript
219
star
17

ember-file-upload

File uploads for Ember apps
TypeScript
201
star
18

emberx-select

Select component for Ember based on the native html select element.
JavaScript
200
star
19

ember-keyboard

An Ember.js addon for the painless support of keyboard events
JavaScript
177
star
20

ember-pikaday

A datepicker component for Ember CLI projects.
JavaScript
159
star
21

active-model-adapter

Adapters and Serializers for Rails's ActiveModel::Serializers
TypeScript
102
star
22

ember-cli-hot-loader

An early look at what hot reloading might be like in the ember ecosystem
JavaScript
99
star
23

ember-autoresize

Autoresize for Ember Components
JavaScript
88
star
24

ember-cli-windows

🚀 Improve Ember-Cli Performance on Windows
JavaScript
79
star
25

ember-set-helper

A better `mut` helper
JavaScript
68
star
26

ember-inputmask

Ember wrapper around Inputmask.js
JavaScript
68
star
27

ember-collapsible-panel

An unopinionated, zero-dependency panel and accordion
JavaScript
57
star
28

ember-qunit-nice-errors

Because expected true, result false is not enough!
JavaScript
56
star
29

ember-cli-ifa

Ember CLI addon for injecting fingerprinted asset map file into Ember app
JavaScript
54
star
30

emberx-file-input

A tiny Ember component which does one thing and only: select files beautifully.
JavaScript
52
star
31

ember-cognito

AWS Amplify/Cognito and ember-simple-auth integration
JavaScript
32
star
32

ember-validators

A collection of EmberJS validators
JavaScript
24
star
33

ember-cli-bugsnag

Integrates Bugsnag reporting service into your Ember CLI app.
JavaScript
20
star
34

ember-stripe-elements

A simple Ember wrapper for Stripe Elements
JavaScript
18
star
35

ember-popper-modifier

An Ember modifier for working with Popper.js.
TypeScript
14
star
36

ember-launch-darkly

A modern Ember addon to wrap the Launch Darkly service
JavaScript
13
star
37

ember-require-module

Dynamically require modules
JavaScript
7
star
38

ember-indexeddb-adapter

Ember Data adapter for IndexedDB
JavaScript
4
star
39

program-guidelines

Checklist and guidelines for the Adopted Ember Addons org.
JavaScript
3
star
40

ember-cli-deploy-new-relic-sourcemap

Ember CLI Deploy plugin to deploy source maps to new relic
JavaScript
2
star