Created
November 28, 2018 11:12
-
-
Save automagisch/870d25938396416f87df73cba8d34655 to your computer and use it in GitHub Desktop.
Simple script to help with paginated AJAX calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import $ from 'jquery'; | |
import EventEmitter from './event-emitter'; | |
export default class Paginator extends EventEmitter { | |
constructor(props={}) { | |
super(); | |
this.props = { | |
url: null, | |
limit: 0, | |
offset: 0, | |
...props | |
} | |
this.events = { | |
request: [], | |
payload: [], | |
error: [] | |
} | |
} | |
// makes a request | |
request() { | |
let { url, current, limit, offset } = this.props; | |
return new Promise((resolve, reject) => { | |
$.get( | |
this.url, | |
response => { | |
resolve(response); | |
this.increment(); | |
}, | |
error => { | |
reject(error); | |
this.emit('error', error); | |
}, "json" | |
); | |
}); | |
} | |
next() { | |
this.props.offset += 1; | |
let { offset, limit } = this.props; | |
this.request().then(response => { | |
this.emit('payload', { offset, response }); | |
}).catch(err => this.emit('error')) | |
} | |
increment() { this.props.current += 1; } | |
get current() { return this.props.current; } | |
get limit() { return this.props.limit; } | |
get offset() { return this.props.offset; } | |
get url() { return `${this.props.url}?offset=${this.offset}&limit=${this.limit}`; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment