forked from rc/aircox
player refresh
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
import {setEcoTimeout} from './utils';
|
||||
import {setEcoInterval} from './utils';
|
||||
import Model from './model';
|
||||
|
||||
export default class Live {
|
||||
@ -7,15 +7,10 @@ export default class Live {
|
||||
this.timeout = timeout;
|
||||
this.src = src;
|
||||
|
||||
this.promise = null;
|
||||
this.items = [];
|
||||
}
|
||||
|
||||
get current() {
|
||||
let item = this.items && this.items[this.items.length-1];
|
||||
if(item)
|
||||
item.src = this.src;
|
||||
return item ? new Model(item) : null;
|
||||
this.interval = null
|
||||
this.promise = null
|
||||
this.items = []
|
||||
this.current = null
|
||||
}
|
||||
|
||||
//-- data refreshing
|
||||
@ -23,12 +18,29 @@ export default class Live {
|
||||
this.promise = null;
|
||||
}
|
||||
|
||||
fetch() {
|
||||
/**
|
||||
* Fetch data from server.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {Function} options.then: call this method on fetch, `this` passed as argument.
|
||||
* @return {Promise} Promise resolving to fetched items.
|
||||
*/
|
||||
fetch({then=null}={}) {
|
||||
const promise = fetch(this.url).then(response =>
|
||||
response.ok ? response.json()
|
||||
: Promise.reject(response)
|
||||
).then(data => {
|
||||
this.items = data;
|
||||
this.items = data
|
||||
|
||||
let item = this.items && this.items[this.items.length-1]
|
||||
if(item) {
|
||||
item.src = this.src
|
||||
this.current = new Model(item)
|
||||
}
|
||||
else
|
||||
this.current = null
|
||||
if(then)
|
||||
then(this)
|
||||
return this.items
|
||||
})
|
||||
|
||||
@ -36,15 +48,30 @@ export default class Live {
|
||||
return promise;
|
||||
}
|
||||
|
||||
refresh() {
|
||||
const promise = this.fetch();
|
||||
_refresh(options={}) {
|
||||
const promise = this.fetch(options);
|
||||
promise.then(() => {
|
||||
if(promise != this.promise)
|
||||
return [];
|
||||
|
||||
setEcoTimeout(() => this.refresh(), this.timeout*1000)
|
||||
})
|
||||
return promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh live info every `this.timeout`.
|
||||
* @param {Object} options: arguments passed to `this.fetch`.
|
||||
*/
|
||||
refresh(options={}) {
|
||||
if(this.interval !== null)
|
||||
return
|
||||
|
||||
this._refresh(options)
|
||||
this.interval = setEcoInterval(() => this._refresh(options), this.timeout*1000)
|
||||
return this.interval
|
||||
}
|
||||
|
||||
stopRefresh() {
|
||||
this.interval !== null && clearInterval(this.interval)
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user